views:

132

answers:

4

Ok, been scratching my head on this one for a bit now... seems related to this ol' chestnut

Here's my problem:

var testlength = theForm.elements.length;
var testlastelement = theForm.elements[testlength].type;

testlength returns 60
BUT!
testlastelement comes back as "undefined" (null or not an object)

What gives?

FWIW, my page has a bunch of inputs (i'm trying to loop through a form and grab names, values, etc)... the form inputs are contained within a table but the last elements (which are also types=image) are outside that table.

+10  A: 

Use testlength - 1. Arrays are zero-based.

Alexander Gyoshev
+1  A: 

You need testlength-1, since arrays are zeo-indexed. That is:

var testlastelement = theForm.elements[testlength-1].type;

Also, camelcase is the javascript standard. Probably better to write this as:

var testLastElement = theForm.elements[testLength-1].type;

At least be consistent. Your variable theForm is camelcased.

Andrew Johnson
Thanks! yeah, i'm a newb... but im learnin'! Still scratching my head on the length count thing though... see above.
MrSparky
+3  A: 

Well, the first element of an array has the index 0, therefore you should try this:

var testlastelement = theForm.elements[testlength-1].type;
Franz
Ok, cool. I get that... but... confusion still reigns... theForm.elements[0] returns a valid element. So what is the length property counting? length = 60, 0 = my 1st element, 60 = ???. My loop no longer errors using the -1 approach... but that's 'cuz it skips the 1st element. Thanks in advance!
MrSparky
oh...wait... *slaps forehead*... thanks!
MrSparky
+4  A: 

Arrays and HTMLCollections like form.elements in JavaScript have 0-based indexes, that means you have 60 elements, and their indexes are from 0 to 59, or from 0 to length-1

CMS
Got it! The length is 60 but it goes from 0 - 59. Thanks!
MrSparky