Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchonise 2 input fields, can it be done using jQuery?

Can jQuery synchronise or copy the text of one input field to another when input A is modified? For example:

<input id="input_A" type="text" /> ...If I type something here

<input id="input_B" type="text" /> ... It will be copied here

Can jQuery Do this?

like image 785
Satch3000 Avatar asked Jan 10 '12 12:01

Satch3000


3 Answers

Try this:

$("#input_A").bind("keyup paste", function() {
    $("#input_B").val($(this).val());
});

For jQuery 1.7+ use on:

$("#input_A").on("keyup paste", function() {
    $("#input_B").val($(this).val());
});

Example fiddle

Update August 2017

The input event is now well supported, so you can use that in place of combining both keyup and paste events:

$("#input_A").on("input", function() {
  $("#input_B").val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input_A" type="text" />
<input id="input_B" type="text" />
like image 73
Rory McCrossan Avatar answered Nov 15 '22 15:11

Rory McCrossan


Late answer, but I prefer this way since it doesn't require multiple element ids:

$('input.sync').on('keyup paste', function() {
     $('input.sync').not(this).val($(this).val());
});

Garrett

like image 36
grimmdude Avatar answered Nov 15 '22 13:11

grimmdude


During writing, pasting, etc value will be copied. In jQuery < 1.7 instead on use bind.

$( "#input_A" ).on( "paste keyup", function() { 
     $( "#input_B" ).val( $( this ).val() );
});
like image 41
abuduba Avatar answered Nov 15 '22 13:11

abuduba