开发者

jQuery - binding multiple events on input fields

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 ev开发者_C百科ents affect performance?


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:

  • Effectively detecting user input in JavaScript

For the performance side of things, each event you described fires at different times so performance shouldn't be an issue unless.


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.


I think there is no performance penalty, unless you do something very slow in handler.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜