getElementsByName() not working? [duplicate]
I have a Javascript function which should update a hidden input field in my form with a number that increments every time the function is called.
It worked originally with getElementById() however because I had to redesign my form I cannot use the php function to assign an individual ID to the element so all I have is a unique name for that element.
So instead I decided to use getElementsByName() from Javascript to modify the element.
Here is the HTML of that element
<input type="hidden" value="" name="staff_counter">
This is my Javascript code:
window.onload=function()
{
//function is activated by a form button
var staffbox = document.getElementsByName('staff_counter');
staffbox.value = s;
s++;
}
I am getting no errors on Firebug when the function is called and the input field is not getting a value given to it.
It was working with getElementById() but why all of a sudden it does not work with getElementsByName()?
- -I have checked that it is the only unique element in the document.
- -I checked for any errors on Firebug when activating the function
Here is the code I use from Codeigniter to make the element
// staff_counter is name and the set_value function sets the value from what is
//posted so if the validation fails and the page is reloaded the form element does
// not lose its value
echo form_hidden('staff_counter', set_value('staff_counter'));
Thanks
Solution 1:
document.getElementsByName()
returns a NodeList, so you have to access it by an index: document.getElementsByName('staff_counter')[0]
(depending on how many of these you have).
You also have access to a length
property to check how many Elements were matched.
Solution 2:
Just had a similar issue, I resolved it with a simple loop over the array. The code below will go through and disable all the buttons with the name of 'btnSubmit'.
for (var i=0;i<document.getElementsByName('btnSubmit').length;i++){
document.getElementsByName('btnSubmit')[i].disabled=true;
}