简体   繁体   中英

How to append character to input field one by one instead of using sth.value() = sth in javascript?

Let's say I have two input fields, Input field A and Input field B. I want to type in Input field A but at the same time the value in input field A also go into input field B.

I know this method can be done by inputfiledB.value() == inputfieldA.value() but I dont want that. I want real time effect like when I type "z" in inputfield A, at the same time inputfield B also has "z". Can anyone help me with this? I really appreciate it. Thank you.

If you only want to do it in response to typing (as compared to all forms of editing including via the Edit menu or drag'n'drop) then add a keyup event handler to the first input that updates the second on each keystroke.

Alternatively, using an input event handler should cover you for Edit menu and drag'n'drop changes as well as typing:

 document.getElementById("a").addEventListener("input", function() { document.getElementById("b").value = this.value; }); 
 label { display: block; margin-bottom: 4px; } 
 <label>Field A: <input id="a"></label> <label>Field B: <input id="b"></label> 

Something like this should work.

<input type="text" id="inputfieldA" onkeyup="syncfield()"></input>
<input type="text" id="inputfieldB"></input>

<script>
function syncfield() {
  var x = document.getElementById("inputfieldA").value;
  document.getElementById("inputfieldB").value = x;
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM