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 -->
<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!
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 -->
<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!
Share Improve this question edited Feb 15, 2013 at 12:49 Vinay 6,8774 gold badges34 silver badges51 bronze badges asked Feb 15, 2013 at 12:46 TJ SmithTJ Smith 231 gold badge1 silver badge3 bronze badges 1-
what will you get if you use
alert(document.getElementsByName("mybox").length);
with the script will it return the total number input tags you have? – Vinay Commented Feb 15, 2013 at 12:59
6 Answers
Reset to default 1getElementsByName
returns an array of 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.
document.getElementsByName("mybox")[j].setAttribute("value", j);
The fist occurrence of j
should be the index of the returned array. If It's the first element found by the given name then 0, if the 2nd, then 1, etc.
document.getElementsByName("mybox")[j].value = j;
Your html code seems wrong, try put the double quotes:
<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.
First variant should work. Just set a value that makes sense.
For testing purposes: document.getElementsByName("mybox")[3].value = "Test";
Also use quotes for attributes type="input"
and name="mybox"
try this $("#mybox").eq(j).val("your value");
thank you for the feedback.
Michal's solution is the one I got working.
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:
//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...