S.SAHT
S.SAHT

Reputation: 61

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

Upvotes: 1

Views: 2960

Answers (3)

Dcdanny
Dcdanny

Reputation: 479

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">

Upvotes: 1

Bilal Ahmed
Bilal Ahmed

Reputation: 257

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()" />

Upvotes: 0

MARSHMALLOW
MARSHMALLOW

Reputation: 1395

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

Upvotes: 1

Related Questions