getElementsByName() not working?

最后都变了- 提交于 2019-11-26 06:46:49

问题


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


回答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.




回答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;
}


来源:https://stackoverflow.com/questions/6967297/getelementsbyname-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!