开发者

.change() only work on select when multiple is on

Looking at the last demo for the .change() jQuery fun开发者_运维技巧ction.

Can someone explain to me why it works there to move with arrows up and down and the value changes, but if I remove the multiple attribute on the select, I must always hit enter before it fires?

Is there a way to fix that?


Remember that the change event only happens if the value of the input element changes. When the user interact with a multi-value select, whether through the mouse or by using the keyboard, the value is changed - you can see that in the demo on the page, as the value of the element is displayed.

For a single value select, however, the value is not changed when you open the dropdown and hover over a value, nor when you do the same with your keyboard. Therefore, the change event is working correctly.


If you want to "workaround" this issue, you can always use the keydown event to catch changes in the value and use that instead. This is a simple example of what such a function might look like:

$('select').focus(function() {
    var v = this.value,
        t = $(this),
        c = t.children(':selected'); // Store the currently selected 
                                     // option element in a variable

    t.keydown(function(e) {
        switch (e.keyCode) {
        case 38:
        case 37:
            c = c.prev().length ? c.prev() : c;
            break;
        case 40:
        case 39:
            c = c.next().length ? c.next() : c;
            break;
        }

        // Do something with this information
        console.log(c.text());
    });
}).blur(function() {
    $(this).unbind('keydown');
});

See a simple demo of this here: http://jsfiddle.net/yijiang/UWaut/


I think that behaviour is caused by the way browsers handle keyboard events on select boxes. For single line select fields, the onchange event is triggered when the value has changed and the focus is moved out of the field, either by pressing enter or tab or by clicking somewhere outside the field. This makes sense in certain scenarios: If you for example want to redirect a user to a different page depending on his selection, you still want him to be able to scroll through the field with the arrow keys without reloading the page after each keypress.

If you explicitly want to call a function each time the user presses an arrow key on the field, use the keyup event.


You'll want to use .keypress() instead.

Here's the page:

http://api.jquery.com/keypress/

By using .keypress() you'll be checking the value each time the key is pressed (mouse or keyboard) and it should work fine across most browsers.

Chrome has the most notable issue with this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜