I want to change the value of an input field in real time as the user types in another input field, preferably using regular JS and not JQuery.
Example: User types a random value into #input_1, and at the SAME TIME, #input_2 receives whatever the user is typing and sets it at its value.
If the user deletes a number from the #input_1 value, #input_2 follows and deletes the same number from its value.
This all in real time and preferably without a button press to trigger the function that does this.
I want to change the value of an input field in real time as the user types in another input field, preferably using regular JS and not JQuery.
Example: User types a random value into #input_1, and at the SAME TIME, #input_2 receives whatever the user is typing and sets it at its value.
If the user deletes a number from the #input_1 value, #input_2 follows and deletes the same number from its value.
This all in real time and preferably without a button press to trigger the function that does this.
Share Improve this question asked Dec 18, 2018 at 17:33 PolarDogPolarDog 431 gold badge2 silver badges7 bronze badges 13- 1 Did you google this? – yaakov Commented Dec 18, 2018 at 17:36
- @YaakovAinspan Tried, but couldn't find anything that fits what I'm looking for. – PolarDog Commented Dec 18, 2018 at 17:38
-
inp1.oninput=x=>inp2.value=inp1.value;
– dandavis Commented Dec 18, 2018 at 17:38 - 1 jsfiddle/yak613/dn6h0fre This took me less than a minute to do :) – yaakov Commented Dec 18, 2018 at 17:38
- Without capturing a button press the only way would be to use a timeout/interval. That would be way less efficient. – James Commented Dec 18, 2018 at 17:39
3 Answers
Reset to default 4Easy ;)
<input id="input1" onkeyup="document.getElementById('input2').value=this.value" />
<input id="input2" />
There are lots of ways to implement this. Here's how I would do it:
HTML:
<input id="sourceField" />
<input id="destinationField" />
JS:
// When the page is done loading and rendering...
window.addEventListener('DOMContentLoaded', ()=>{
// Get the appropriate elements
const sourceField = document.getElementById('sourceField')
const destinationField = document.getElementById('destinationField')
// When the user types some input into the first text field...
sourceField.addEventListener('input', ()=>{
// Set the value of the destination field to the value of the source field.
destinationField.value = sourceField.value
})
})
you can do it like this
You need to select the first input (on an event) and take value from that input and update in the second one.
function handle(e){
var input1 = document.getElementById('input1').value;
console.log(input1)
document.getElementById('input2').value = input1;
}
<input id='input1' onkeyup="handle()" value=""/>
<input id='input2' value="" />