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

I have the following which works as long as I use the mouse to select an option from the selectbox, or

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());
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745061983a4609020.html

相关推荐

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

    I have the following which works as long as I use the mouse to select an option from the selectbox, or

    17小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信