jQuery multiple events to trigger the same function

shaneburgess picture shaneburgess · Mar 28, 2010 · Viewed 637.9k times · Source

Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do them separately?

The problem I have is that I need to validate some data with a db lookup and would like to make sure validation is not missed in any case, whether it is typed or pasted into the box.

Answer

Tatu Ulmanen picture Tatu Ulmanen · Mar 28, 2010

You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {
   ...
}

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)