Ionut Flavius Pogacian
Ionut Flavius Pogacian

Reputation: 4801

jQuery: Do I need both keyUp and change events?

I have a page with 2 forms; each form has an input text field;

The value found in the input text of the 1st form must be the same with the value found in the input text of the 2nd form;

When the value changes, the other input text field also modifies its value;

Should I use both onkeyup and onchange events?

If not, which one is the right one to use?

I am asking this because it seams that I have 2 post requests, and I think that this is why.

   $('input.searchbox').keyup( function(){
       $('input.txtfieldsearch').val($('input.searchbox').val());
       listViewUpdate();
       $('input.txtfieldsearch').trigger("keyup");
   });
                
    $('input.txtfieldsearch').keyup( function(){
       $('input.searchbox').val($('input.txtfieldsearch').val());
       listViewUpdate();
    });
                
   $('input.searchbox').change( function(){
       $('input.txtfieldsearch').val($('input.searchbox').val());
       listViewUpdate();
       $('input.txtfieldsearch').trigger("change");
   });
                
    $('input.txtfieldsearch').change( function(){
       $('input.searchbox').val($('input.txtfieldsearch').val());
       listViewUpdate();
    });

Upvotes: 34

Views: 53345

Answers (4)

SeinopSys
SeinopSys

Reputation: 8937

onkeyup mostly fires when a key was pressed by the user and then released. onchange can happen if the user uses the browser's autocomplete feature. You should use the .on() method to catch both events, just in case:

$('input.searchbox').on('keyup change', function(e){
    $('input.txtfieldsearch').val($('input.searchbox').val());
    listViewUpdate();
    $('input.txtfieldsearch').trigger(e.type);
});

$('input.txtfieldsearch').on('keyup change', function(){
    $('input.searchbox').val($('input.txtfieldsearch').val());
    listViewUpdate();
});

Upvotes: 11

rigobcastro
rigobcastro

Reputation: 1257

You can use $.on() function and attach multiples handlers.

$("#element").on('keyup change', function (){
   // Your stuff...
});

Upvotes: 58

Swarup Sengupta
Swarup Sengupta

Reputation: 131

You can use only "input" event if you don't need to provide support for the older browsers. It will be fired everytime a value changes in the input element. Here's a list of the supported browsers: https://developer.mozilla.org/en-US/docs/Web/Events/input

Upvotes: 12

ColBeseder
ColBeseder

Reputation: 3669

If you want to react to change, you should use change.

There are some occasions where a keyup doesn't make a change(like shift) and occasions where there's a change without a keyup (paste).

Upvotes: 2

Related Questions