0

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.

1
  • 1
    60 would be outside the array of size 60. last element ends at lenght[59] Commented Nov 3, 2009 at 18:57

4 Answers 4

10

Use testlength - 1. Arrays are zero-based.

Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

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

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

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

1 Comment

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!
1

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.

1 Comment

Thanks! yeah, i'm a newb... but im learnin'! Still scratching my head on the length count thing though... see above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.