简体   繁体   中英

How to Copy Value from one Input Field to Another Using JS

I have two inputs fields:

<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />

I want a function to copy the text of the first input automatically when we click on the second input without using Jquery

Thanks

A basic way of doing this:

 <input type="text" id="one" name="one"> <input type="text" id="two" name="two" onfocus="this.value = document.getElementById('one').value">

To check if the user clicks on the <input> element, add an event listener to it.
Then, get the value of the first text field using the value property.

Here is your code:

 document.getElementById('two').addEventListener("click", function() { this.value = document.getElementById('one').value; });
 <input type="text" id="one" name="one" /> <input type="text" id="two" name="two" />

Here is a living demo: https://codepen.io/marchmello/pen/XWmezNV?editors=1010

here is the example to do this.

 var one = document.getElementById("one"); var two = document.getElementById("two"); function myFunction(){ two.value = one.value; }
 <input type="text" id="one" name="one" /> <input type="text" id="two" name="two" onfocus="myFunction()" />

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