[英]set value to array of getElementsByName
I am having the following situation: 我遇到以下情况:
I have tried the following, but get into syntax problem: 我尝试了以下方法,但是陷入语法问题:
<!-- html part -> this row will be replicated by the dynamic table code --> <!-html部分->此行将由动态表代码复制->
<tr><td><input type=input name=mybox></td></tr> //js part - variant 1: document.getElementsByName("mybox").item(j).value = j; //js part - variant 2: document.getElementsByName("mybox")[j].setAttribute("value", j);
None of these seems to work. 这些似乎都不起作用。 Can you suggest a right way to do it? 您能建议正确的方法吗?
Thanks! 谢谢!
getElementsByName
returns an array of HTMLElements. getElementsByName
返回一个HTMLElements数组。
This line has the correct syntax but I doubt j
, the value you are trying to set is the right index value of the returned array. 该行的语法正确,但是我怀疑j
,您尝试设置的值是返回数组的正确索引值。
document.getElementsByName("mybox")[j].setAttribute("value", j);
The fist occurrence of j
should be the index of the returned array. j
第一个出现应该是返回数组的索引。 If It's the first element found by the given name then 0, if the 2nd, then 1, etc. 如果它是通过给定名称找到的第一个元素,则为0,如果是第二个,则为1,依此类推。
document.getElementsByName("mybox")[j].value = j;
您的html代码似乎有误,请尝试使用双引号:
<tr><td><input type="input" name="mybox"></td></tr>
We don't know what is the value of j
and how it's being set. 我们不知道j
的值是什么以及如何设置。
First variant should work. 第一个变体应该起作用。 Just set a value that makes sense. 只需设置一个有意义的值即可。 For testing purposes: document.getElementsByName("mybox")[3].value = "Test";
出于测试目的: document.getElementsByName("mybox")[3].value = "Test";
Also use quotes for attributes type="input"
and name="mybox"
还对属性type="input"
和name="mybox"
使用引号
试试这个$("#mybox").eq(j).val("your value");
thank you for the feedback. 感谢您的反馈。
Michal's solution is the one I got working. Michal的解决方案是我得到的解决方案。
document.getElementsByName("mybox")[3].value = "Test";
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ============================================
However I tried my 2nd variant as suggested by Marcell Fülöp in a very rudimentary way and saw some strange behaviour: 但是,我以非常基本的方式尝试了MarcellFülöp建议的第二个变体,并看到了一些奇怪的行为:
//manual assignment of indexes
document.getElementsByName("mybox")[0].setAttribute("value",0);
document.getElementsByName("mybox")[1].setAttribute("value",1);
document.getElementsByName("mybox")[2].setAttribute("value",2);
The strange result was only the 1st box got it's value. 奇怪的结果是只有第一个盒子才值钱。 I'd be happy to understand why... 我很高兴明白为什么...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.