0

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 />
0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

@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 names you're creating an Array. Duplicating ids 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.