getElementsByName() not working? [duplicate]
Asked Answered
H

2

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

Hamamatsu answered 6/8, 2011 at 13:59 Comment(1)
check this out https://mcmap.net/q/585295/-javascript-getelementbyname-and-focusCoenesthesia
L
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.

Lockard answered 6/8, 2011 at 14:3 Comment(1)
It's not an array. It's a NodeList. Big difference.Silverware
B
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;
}
Bluing answered 10/1, 2013 at 22:57 Comment(1)
move getElements... out of the cycle var _elements = document.getElementsByName('btnSubmit'); for (var i=0;i<_elements.length;i++){ _elements[i].disabled=true; }Hexapartite

© 2022 - 2024 — McMap. All rights reserved.