Looping through form objects with the same name in JS

I am using JS for validating user input.  The amount of lineitems that appear depend on the # of recors in the DB.  If I have more than 1 record my code works becuae I loop through the name of that textbox and i (in brackets of course).  ]The problem is when there is one record-only one text box.  Js doesn't create an array so textboxname 0 is null.  I assumed that if there is one textbox it would have 0as its index.  How can  I code for this scenario?  thanks
JSCFAsked:
Who is Participating?
 
Justin MathewsConnect With a Mentor Commented:
Use the loop only if textbox.length is defined else use textbox.value to get the only element's value.

if (document.forms[0].textbox.length)
//loop
else
val = document.forms[0].textbox.value;
0
 
JSCFAuthor Commented:
OK, but I was wondering about this because I have another page where users can add records.  If there is an error in user input.  It returns that one record-I loop through it in a very similar way and I do not get an error that time even though there is one textbox with that name on the page-wht is that?
0
 
Justin MathewsCommented:
I can't say why it is happening. Generally the rule of the thumb is if you have multiple elements with the same name you get a collection otherwise you get a single element.
0
 
JSCFAuthor Commented:
Is this common practice to allow for these two scenarios and basically repeat the code twice-when validating with JS?
0
 
Justin MathewsConnect With a Mentor Commented:
Yes, it is safest to do so. Or you should think of giving different names for the text boxes like textbox1, textbox2, etc.
0
All Courses

From novice to tech pro — start learning today.