我有一个 JavaScript 函数,每次被调用时应该更新表单中的隐藏输入字段,使其显示的数字递增。
最初它使用了 getElementById(),但由于我必须重新设计我的表单,所以我无法使用 PHP 函数为该元素分配一个独特的 ID,因此我只有一个唯一名称来识别该元素。
因此,我决定改用 JavaScript 中的 getElementsByName() 来修改该元素。
这是该元素的 HTML 代码:
<input type="hidden" value="" name="staff_counter">
这是我的 JavaScript 代码:
window.onload=function()
{
//function is activated by a form button
var staffbox = document.getElementsByName('staff_counter');
staffbox.value = s;
s++;
}
当调用函数并且输入字段没有给定的值时,Firebug上没有错误提示。
使用getElementById()时它是有效的,但为什么突然使用getElementsByName()不起作用了?
- - 我已经确认它是文档中唯一的元素。
- - 在激活函数时,我检查了Firebug上是否有任何错误。
以下是我从Codeigniter中使用的代码来创建该元素:
// 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'));
谢谢