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.
The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the
.on()
method.I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:
My workaround have been to first define the function,
and then handle the events individually
This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue
If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).
It sounds like what you actually want is something like this:
"Is there a way to have
keyup
,keypress
,blur
, andchange
events call the same function in one line?"It's possible using
.on()
, which accepts the following structure:.on( events [, selector ] [, data ], handler )
, so you can pass multiple events to this method. In your case it should look like this:And here is the live example:
You could define the function that you would like to reuse as below:
And later you can set however many event listeners you want on your object to trigger that function using on('event') leaving a space in between as shown below:
You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:
Another option is to use chaining support of jquery api.
This tutorial is about handling multiple events.