Reputation: 68450
I was wondering if binding a single change()
event on form fields is enough to correctly perform a action when the value of the field changes.
Or should I bind all possible events? like this:
$(this).bind('change keyup focus click keydown', function(){
// ...
}).change();
Also, does binding multiple events affect performance?
Upvotes: 1
Views: 4729
Reputation: 235992
The problem doing this:
$(this).bind('change keyup focus click keydown', function(e) { // ...
is that you would have to figure out which event actually was fired, entering the event handler.
switch(e.type) {
case 'change': {
break;
}
case 'focus': {
break;
}
// ...
}
I would just bind a change
event if that is enough for you. You're getting in a lot of trouble when doing stuff on all those events, because click
fires before change
, focus
after click
etc. etc. This hurts to figure out and act properly.
Upvotes: 1
Reputation: 344567
change
will only fire when the field loses focus (for most inputs). If you want something a little more real time, use the HTML 5 oninput
event. This will pretty much catch any type of value change for an input element (and it bubbles, too!). It's not supported in Internet Explorer 8 and lower, though, but I wrote a plugin that maps to onpropertychange
for those browsers.
See also:
For the performance side of things, each event you described fires at different times so performance shouldn't be an issue unless.
Upvotes: 3
Reputation: 816394
Only listening to the change
event might be sufficient for you (see also @Andy E's answer). From the documentation:
The
change
event is sent to an element when its value changes. This event is limited to<input>
elements,<textarea>
boxes and<select>
elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
Upvotes: 2
Reputation: 29831
Each event happens at a different time. There may be some overlap however depending on what you are doing they may be very different. For example a keyup
event happens after the value has already been updated on the input
. Whereas the keydown
happens before. This can enable you to stop a value from ever entering the textbox.
As far as performance goes, you are running code for five different events in this example. Compared to a single event. At least your code should differentiate the overlap between events.
Upvotes: 1
Reputation: 11658
I think there is no performance penalty, unless you do something very slow in handler.
Upvotes: 1