Dave Dave - 15 days ago 4
jQuery Question

In jQuery, how do I trigger an action on a keypress but only if the focus is not on a form field?

I’m using jQuery 1.11. I want to run an action if the user presses the “d” key on the keyboard. So I have this

$(document).keypress(function(e) {
if(e.which == 68 || e.which == 100) {
submitDownloadUsersReq();
}
});


However, if they press the “d” key while within a text box, I don’t want the above action to be triggered. How can I modify the above so that I will not trigger the action if the user is messing around with a form field?

Answer

You could check the type of element using e.target and is():

$(document).keypress(function(e) {
    if (!$(e.target).is(':input') && (e.which == 68 || e.which == 100)) {
        submitDownloadUsersReq();
    }
});

Note that the :input selector will match input, select, textarea and button.