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?
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
.