Reputation: 49
When I wrote something in the first input, second input showed it, but:
a) What if i want see text from input "2" showed in input "3"?
HTML:
<input id="1" type="text" oninput=al() /></br>
<input id="2" disabled="disabled" ></br>
<input id="3" disabled="disabled">
JS:
function al() {
var a = document.getElementById("1").value;
var result = a;
var ab = document.getElementById("2");
ab.value=a;
}
b) What if I want to see text from input "1" in two inputs named "2"? HTML:
<input id="1" type="text" oninput=al() /></br>
<input id="2" disabled="disabled" ></br>
<input id="2" disabled="disabled">
JS:
function al() {
var a = document.getElementById("1").value;
var result = a;
var ab = document.getElementById("2");
ab.value=a;
}
Upvotes: 0
Views: 299
Reputation: 1634
First of all, you can't have two element with the same ID.
Second to copy from one to another, it's better use the keyDown
, keyUp
or onchange
events.
E.g.
<input type="text" id="1" onchange="copypaste()"/>
<input type="text" id="2"/>
function copypaste() {
var first = document.getElementById("1")
var second = document.getElementById("2")
second.value = first.value
}
Upvotes: 0
Reputation: 16693
Answer A: To show the same value in an input with ID 2
and an input with ID 3
:
function al() {
var a1 = document.getElementById("1").value;
var a2 = document.getElementById("2");
var a3 = document.getElementById("3");
a2.value = a3.value = a1;
}
Answer B: Using elements with the same ID is wrong and will result in an invalid HTML document. To achieve your goal, you can set both elements with a certain class (classA
at the example below), then you can use document.querySelectorAll
which returns an array of elements, and then set their value with an index [0]
and [1]
:
<input id="1" type="text" oninput=al() /></br>
<input class='classA' disabled="disabled" ></br>
<input class='classA' disabled="disabled">
function al() {
var a = document.getElementById("1").value;
var result = a;
var ab = document.querySelectorAll("[class='classA']");
ab[0].value = ab[1].value = a;
}
Upvotes: 2