tags:

views:

35

answers:

3

i have two textbox1 and textbox 2..when i start typing in textbox 1, textbox 2 should automatically have the same chars inserted..similarly wehn i type in textbox 2, textbox1 should get updated. Any ideas?

A: 
$('#textbox1').change (function(){ $('#textbox2').val($(this).val()); });
$('#textbox2').change (function(){ $('#textbox1').val($(this).val()); });
MiffTheFox
+1  A: 

Using the change event would work if you want the second box updated only after the textbox loses focus. If you use keyup, then each character as you type would show up in the other box.

$('#textbox1').keyup(function(){ $('#textbox2').val($(this).val()); });
$('#textbox2').keyup(function(){ $('#textbox1').val($(this).val()); });

Edit:

Here's an alternate way that would meet your requirement of combining them (and would allow you to chain any number of textboxes together). It's similar idea to what Q8-coder was trying to do with his answer, but the use of the this keyword for retrieving the value makes all the difference.

You would put the class "mimic" on both of the textboxes.

$(document).ready(function() {
   $('input.mimic').keyup(function() {
        var text = $(this).val();
        $('input.mimic').val(text);
   });
});

Edit:

Now that Q8-coder has corrected his answer, this alternative is the same as his answer (though it does help speed up the selector by narrowing it to input elements).

patmortech
Can these two statements be combined?
Hitz
See my edit for an alternative.
patmortech
A: 

you can add class '.mytext' to both textboxes and align them with below jquery script.

$(".mytext").keyup(
  function(){
    var teks = $(this).val();
    $(".mytext").val(teks);        
  }
);
Anwar Chandra
This only works to copy the first box value to the second. If you try to type into the second box it will automatically copy the value from the first box again and whatever you typed will be gone.
patmortech
ooh yes! I meant to type $(this).val() instead of $(".mytext").val();
Anwar Chandra