开发者

Jquery: Mirror one text input to another

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


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).


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'); 


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());  
});


Simple: http://jsfiddle.net/brynner/KnXJc/

HTML

<input type="text" class="mirror" placeholder="one">
<input type="text" class="mirror" placeholder="two">

jQuery

$('.mirror').on('keyup', function() {
    $('.'+$(this).attr('class')).val($(this).val());
});


$( document ).ready(function() {

    console.log( "ready!" );

   /*  $( ".checking" ).blur(function() {
          alert( "Handler for .blur() called." );
        }); */
        $(".formula_open").click(function(){
            getval();
         function getval(){
        var schedulenameexpression= $('.idfield1').val();
        var res = schedulenameexpression.split(/[\s()+*-/]+/);
        var i,text,substri,newitem;

        for (i = 0; i < res.length; i++) {
            text = res[i];
           substri = text.substr(6);
            var name ="schid_"+substri;
            var schname = $('#'+substri).val();
            console.log( schname );
            schedulenameexpression = schedulenameexpression.replace("schid_"+substri, $("#"+substri).val());
        }
         $('.idfield2').val(schedulenameexpression);
        }

    $('.idfield1').bind('keypress keyup blur propertychange', function() {
        getval();

});
});
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜