Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Mirror one text input to another

Tags:

jquery

I'm wanting to have one text field autopopulate with whatever the other text field has being typed into it.

How do I go about this?

Thank you! Hudson

like image 308
atwellpub Avatar asked Jun 04 '10 20:06

atwellpub


3 Answers

Short and simple:

$('#idfield1').keypress(function() {
    $('#idfield2').val($(this).val());
});

or to bind it to several events in order to update it also if it loses focus:

$('#idfield1').bind('keypress keyup blur', function() {
    $('#idfield2').val($(this).val());
});

Reference: .keypress(), .val(), .blur(), .bind()

Update:

Due to, for me, mysterious reasons, when the first character is typed in, it is not set in the other input field. Has anyone any idea? ;)

It works though by using keyup (keydown also produces the same strange result).

like image 72
Felix Kling Avatar answered Oct 08 '22 21:10

Felix Kling


Dustin Diaz has written a wonderful mirror for Twitter Widget using jQuery

$.fn.mirror = function (selector) {
    return this.each(function () {
        var $this = $(this);
        var $selector = $(selector);
        $this.bind('keyup', function () {
            $selector.val(($this.val()));
        });
    });
};

Use it like

$('#source_text_id').mirror('#destination_text_id'); 
like image 7
naveen Avatar answered Oct 08 '22 23:10

naveen


For an alternative:

$('#idfield1').bind('keyup keypress blur', function() 
{  
      $('#idfield2')[0].value = $(this)[0].value; 
});

or

$('#idfield1').bind('keyup keypress blur', function() 
{  
    $('#idfield2').val($(this).val()); 
});

For more recent version of jQuery you can also use .on

$('#idfield1').on('keyup keypress blur', function() 
{  
      $('#idfield2').val($(this).val());  
});
like image 6
Mark Schultheiss Avatar answered Oct 08 '22 22:10

Mark Schultheiss