问题描述:

I have two text boxes, when i type something in the first text box it should reflect in the second textbox. i am trying to achive this in key up event, when i do the following it replaces the value of text2 with the value of text1.But i don't want to replace the value in text2, i want to pick the newly typed values from text1 and append it to text2.

Here text2 contains some values which is not there in text1 so i can't use

 $('.text2').val($('.text2').val()+$(this).val());

<input class='text1'>

<input class='text2'>

$(".text1").live("keyup",function(e) {

$('.text2').val($(this).val());

});

网友答案:

There is another way to do it. You can assign a cssClass to textboxes which you want to sync and then use below jQuery to achieve the above functionality.

$(document).ready(function() { $('.dummyClass').keyup(function(e) { var txtVal = $(this).val(); $('.dummyClass2').val($('.dummyClass2').val() + txtVal); }); });

网友答案:

use this

 $(".text1").on("keyup",function(e) {
 var text2val = $('.text2').val();
 $('.text2').val(text2val  + $(.text1).val());
 });

OR

$(".text1").on("keyup",function(e) {
     var text2val = $('.text2').val();
     var text1val = $(this).val();
     $('.text2').val(text2val  + text1val);
     });
网友答案:
var temp = "";

$( ".text1" ).keyup(function() {
if(temp !== ""){
    $('.text2').val($('.text2').val().slice(0, -temp.length));
}
var $text1= $(this).val();
    temp = $text1;
    $('.text2').val($('.text2').val() + $text1);
});
$(".text2").keyup(function(){
    temp = "";
});

Fiddle

相关阅读:
Top