getElementsByName()不工作? [英] getElementsByName() not working?
问题描述
我有一个Javascript函数,它应该更新隐藏的输入字段在我的形式,每次调用函数时递增一个数字。
strong> getElementById()但是因为我不得不重新设计我的形式我不能使用PHP函数分配一个单独的ID的元素,所以我有一个唯一的名称为该元素。
因此,我决定使用Javascript中的 getElementsByName()来修改元素。
< input type =hiddenvalue =name =staff_counter>
这是我的Javascript代码:
window.onload = function()
{
//函数由表单按钮激活
var staffbox = document .getElementsByName('staff_counter');
staffbox.value = s;
s ++;
}
当调用函数时,Firebug没有错误,
它使用getElementById(),但是为什么突然不能使用getElementsByName()?- - 我已检查它是文档中唯一的唯一元素。
-
以下是Codeigniter使用的代码:
$ b b $ b// staff_counter是名称,set_value函数从
//发布的值设置值,如果验证失败,页面重新加载表单元素
//不会丢失它的值
echo form_hidden('staff_counter',set_value('staff_counter'));
感谢
解决方案document.getElementsByName()
返回一个数组,所以你必须通过索引访问它:document.getElementsByName('staff_counter' )[0]
(取决于你有多少)。
您还可以访问
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
解决方案document.getElementsByName()
returns an array, 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.这篇关于getElementsByName()不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文