Assign value for multiple input boxes using javascript?
It only assigns a value to one of because ID's should be unique; therefore you're only actually going to end up targetting the first one with that value assignment.
Change your HTML to use a class instead:
<input type="text" class="myids"><br>
<input type="text" class="myids"><br>
<input type="text" class="myids"><br>
<input type="text" class="myids"><br>
Then, you can adapt your JavaScript accordingly.
jQuery
in jQuery, you could then set a value using:
$('.myids').val('value for all of them here');
jQuery jsFiddle here.
Pure JavaScript
In Javascript, you'd use getElementsByClassName()
and iterate through them, giving them the same value.
var x = document.getElementsByClassName('myids');
for(i = 0; i < x.length; i++) {
x[i].value = "New!";
}
Pure JavaScript jsFiddle here.
The id
attribute is supposed to be unique so having the same id
several times is invalid html and most browsers will simply ignore any inputs with id
s that already exist int he dom tree.
Sidenote: To set the value of several ids (via jquery) use the val()
function and a selector that selects all respective inputs like this (it looks alot more cleaner to have this in a one-liner as opposed to sticking to pure javascript):
$('#myid1, #myid2, .myclass1').val('new value');