Search code examples
javascriptjqueryonkeyup

onKeyUp with one input field affecting another with jQuery?


I've got 2 input fields. They are both currently populated.

Input 1 = "Name"
Input 2 = "Name says this: blah blah blah"

I'm trying to figure out how to bind an onKeyUp event to both of them so that when Input 1 is changed, it will also change the value of input 2.

For example:

Input 1 = "Bla"
Input 2 = "Bla says this: blah blah blah";

I was thinking a regex, but what if it searched for "bla" on input 2, and returned 4 occurrences? That's why I was thinking of just maybe getting rid of everything after the first space in Input 2 and always replacing that value.

This is what I was kind of thinking of doing:

        $('#input-1').bind('keyup', function() {
        $('#input-2').val().append($('#input-1'));
    });

Obviously that code doesn't work, but can anyone point me to the right direction? Should I make a variable and put it in the beginning of the input box (of input 2)?

EDIT:

This is the code that ended up working, which also doesn't delete the additional info if there is any in input-2's box:

var name = $('#input-1').val();
var text = " wanted to tell you something;

$('#input-1').bind('keyup keypress blur', function() {
   name = $(this).val();
$('#share-message').val(name + text);
});

Solution

  • try

    $('#input-1').bind('keyup keypress blur', function() {
        var input2  = $('#input-2').val();
        var input1   = $(this).val();
        $('#input-2').val(input2+input1);
      });