Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop over elements in form using getElementsByName?

I would like to select certain elements in form by their name, so I suppose using getElementsByName(name). Then I would like to add a value to these elements. How do I do this loop?

boxesEL = document.getElementsByName(boxesName);

for(var x=0;x<=boxesEL.length;x++){
    boxesEL[x].value = "some value";
}

I'm getting an error boxesEL[x] is undefined.

like image 792
Adriana Avatar asked Sep 29 '09 21:09

Adriana


People also ask

How do I loop over getElementsByTagName?

After selecting elements using the querySelectorAll() or getElementsByTagName() , you will get a collection of elements as a NodeList . To iterate over the selected elements, you can use forEach() method (supported by most modern web browsers, not IE) or just use the plain old for-loop.

What does getElementsByName return?

getElementsByName() The getElementsByName() method of the Document object returns a NodeList Collection of elements with a given name attribute in the document.

How do you get getElementsByName value?

How it works: First, select the submit button by its id btnRate using the getElementById() method. Second, listen to the click event of the submit button. Third, get all the radio buttons using the getElementsByName() and show the selected value in the output element.


1 Answers

Take out the "=" sign in the comparison in the for loop. You're looping one too many times. Length gives you the number of elements - the maximum index of the collection will be one less, because it's zero based.

for(var x=0; x < boxesEL.length; x++)   // comparison should be "<" not "<="
{
    boxesEL[x].value = "some value";
}
like image 176
womp Avatar answered Nov 09 '22 15:11

womp