最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fire .change with keyup and keydown - Stack Overflow

programmeradmin0浏览0评论

I have the following which works as long as I use the mouse to select an option from the selectbox, or use keyboard arrow keys to select the option, but when using the keyboard, the change event does not fire until I press enter on the keyboard.

How would I detect a change using the keyboard arrow keys without having to press enter?

$('#select_box').change(function() {
    some_function($(this).val());
});

I have the following which works as long as I use the mouse to select an option from the selectbox, or use keyboard arrow keys to select the option, but when using the keyboard, the change event does not fire until I press enter on the keyboard.

How would I detect a change using the keyboard arrow keys without having to press enter?

$('#select_box').change(function() {
    some_function($(this).val());
});
Share edited Jun 3, 2011 at 14:05 Lightness Races in Orbit 386k77 gold badges666 silver badges1.1k bronze badges asked Jun 3, 2011 at 13:41 oshirowanenoshirowanen 16k83 gold badges205 silver badges357 bronze badges 1
  • 1 does below answers not satisfactory?? – xkeshav Commented Jun 3, 2011 at 14:33
Add a ment  | 

3 Answers 3

Reset to default 4

You'll probably want to avoid calling your function multiple times unnecessarily, which will happen if you are not careful with multiple events. You can avoid this by checking if the value of the field has actually changed before calling it. One way of doing this, shown below, is to store a property on the field with the previous value and then using that to check if the field's value has changed before calling your function:

var previousValuePropertyKey = 'previousValue';

$('#select_box').bind('keyup change', function(event) {
    var previousValue = $(this).prop(previousValuePropertyKey);
    var currentValue = $(this).val();
    $(this).prop(previousValuePropertyKey, currentValue );

    if(previousValue != currentValue ){
        alert(currentValue);//TODO remove alert
        //Yourfunction(..);
    }
});

Here's a fiddle for an example.

TRY

$('#select_box').bind('keyup change',function() {
    some_function($(this).val());
});

Reference

$('#select_box').change(function() {
    alert($(this).val());
});

$('#select_box').keyup(function() {
    alert($(this).val());
});
发布评论

评论列表(0)

  1. 暂无评论