Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: trigger event on tab key

I would like to call a function when the tab key is pressed within any field with the name="notes".

I tried the following but this doesn't fire (using IE 9). What do I have to change here to make this work at least in IE 8 and IE 9 ?

$('input[name=notes]').keypress(function(e) {
    var code = e.keyCode || e.which;
    if (code === 9) {  
        e.preventDefault();
        myFunction();
    }
});
like image 650
user2571510 Avatar asked Apr 16 '14 14:04

user2571510


1 Answers

The problem I think is in the type of event you're trying to listen to. The keypress event is triggered when a char gets written into an input text, while tab key doesn't insert any character. It just blurs the input. Read more here.

You might be looking for the keydown event instead.

Have a look at this fiddle. Would it help to get you started?

JS

$('input[name=notes]').keydown(function(e) {
    var code = e.keyCode || e.which;

    if (code === 9) {  
        e.preventDefault();
        myFunction();
        alert('it works!');
    }
});
like image 89
Nicolae Olariu Avatar answered Sep 20 '22 22:09

Nicolae Olariu