17

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Satch3000
  • 47,356
  • 86
  • 216
  • 346

4 Answers4

26

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" />
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
7

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

grimmdude
  • 374
  • 4
  • 7
3

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() );
});
abuduba
  • 4,986
  • 7
  • 26
  • 43
  • The `focus` is unnecessary and `keydown` happens before value changed. Rory has it correctly. – Ilia G Jan 10 '12 at 12:46
-1

Yes, it can. Bind a keypress or keyup event and copy over the value:

$('#input_A').keyup(function() {
    $('#input_B').val($(this).val());
});

Or, if you only want the value to be copied after the user is finished editing it, use the blur event with the same handler. This has an added advantage that if the user pastes text into input_A, it also will be copied into input_B.

$('#input_A').blur(function() {
    $('#input_B').val($(this).val());
});

Here's a working example with keyup and one with blur.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91