Reputation: 17
how to copy value from one text input to array text input
<script>
function sync()
{
var n1 = document.getElementById('n1');
var n2 = document.getElementById('n2');
n2.value = n1.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync()"><br />
<input type="text" name="n2[]" id="n2"/><br />
<input type="text" name="n2[]" id="n2"/><br />
<input type="text" name="n2[]" id="n2"/><br />
<input type="text" name="n2[]" id="n2"/><br />
<input type="text" name="n2[]" id="n2"/><br />
Upvotes: 0
Views: 334
Reputation: 51721
@Arun has already explained how to achieve what you want through a for
loop and using id
correctly. I would just like to add to his answer and clear up any confusion that you might have.
When you duplicate name
s you're creating an Array. Duplicating id
s is just plain wrong as they are identifier(s) and have to be unique.
Note that there's NO getElement(s)ById() function. It's getElementByID()
as it's supposed to return the one single element that's associated with this identifier.
Also note that you didn't receive any Javascript errors there and getElementById()
simply returned the first text input associated with id n2
.
Upvotes: 0
Reputation: 388416
As I pointed out in the comments id
attribute should be unique in a page, ie there should be only one element with an id. In your case you have many elements with id n2
If I understand the requirement, you want to copy the value of n1
to all n2
elements. You can use the getElementsByName to achieve this
function sync() {
var n1 = document.getElementById('n1');
var n2s = document.getElementsByName('n2[]');
for(var i=0; i<n2s.length;i++){
n2s[i].value = n1.value;
}
}
Demo: Fiddle
Upvotes: 1