简体   繁体   中英

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

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!');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM