i want send a key event to simulate mytext2 from mytext1 . that means when i type "a" in mytext1 it should display in mytext2 also.further when i press backspace on mytext1 it should be affected in to mytext2 also. in some case mytext1 has nothing but mytext2 remaining something,in such a case when i press backspace on mytext1 it should be clear last letter in mytext2 ('it says that i don't want both text box content to be equal'). here is my code:

$('#mytext1').on('keydown',function(e){
  var keyCode = e.keyCode || e.which;

  $('#mytext2').trigger($.Event("keypress", { keyCode: keyCode }));
});

$('#mytext1').on('keypress',function(e){
  var keyCode = e.keyCode || e.which;
  this.val()+=keyCode;
});

 <input type='text' id='mytext1' value='this not eq to txt2'/>
  <input type='text' id='mytext2'value='this not eq to txt1'/>

* even delete, backspace event shuld be trigger to mytext2. just like i'm doing it on mytext2.think that i put same key press on different text box initially with different content

thnks,help me. ------------------update------------------------------------------------------------------- think initially mytext1 has a value "ca" mytext2 has "bea" , when i press "t" on mytext1 it should be affected in to mytext2 . then mytext1 willbe "cat" mytext2 willbe "beat". if i press backspace twice in mytext1 it will be resulted as mytext1=>"c" ,mytext2=>"be". sorry for my poor explaninig.

有帮助吗?

解决方案 2

http://jsfiddle.net/coma/kNPRM/4/

$(function() {

    var a = $('#a');
    var b = $('#b');

    var foo = function(input, string, code) {

        switch(code) {

            case 8:
                var s = input.val();
                input.val(s.substr(0, s.length -1));
                break;

            default:
                var c = String.fromCharCode(code);

                if(c.match(/\w/)) {

                    input.val(input.val() + string.slice(-1));

                }

        }

    };

    a.on('keyup', function(event) {

        foo(b, this.value, event.keyCode);        

    });

    b.on('keyup', function(event) {

        foo(a, this.value, event.keyCode);

    });

});

其他提示

http://jsbin.com/urilox/1/edit

$('#mytext1').on('input', function() {
  $('#mytext2').val(this.value);
} );

If you need to handle a "Paste" event also this is a good way to go. (Modern browsers)
Non-modern use: keyup paste propertychange


For an intercommunication between them - do like:

$('#mytext1, #mytext2').on('input', function() {
  $(this).siblings().val(this.value); // put both your inputs strictly inside a neutral parent!
} );

or simply

var $a=$('#mytext1'), $b=$('#mytext2');

$a.on('input', function() {
  $b.val(this.value);
} );
$b.on('input', function() {
  $a.val(this.value);
} );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top