23

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

sqlmole
  • 997
  • 7
  • 17
  • 31

2 Answers2

35

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.

Munim Munna
  • 17,178
  • 6
  • 29
  • 58
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
  • 7
    It's **not** an array. It's a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F). Big difference. – Pacerier Mar 01 '15 at 19:36
4

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;
}
Louis
  • 71
  • 1
  • 1
  • 5
  • move getElements... out of the cycle var _elements = document.getElementsByName('btnSubmit'); for (var i=0;i<_elements.length;i++){ _elements[i].disabled=true; } – andrej Jan 28 '14 at 09:55