Jquery keydown but ignore if in textbox

I call a function (below) that will execute the action if the user clicks the delete button. It works fine, but I need to do this only on the page, and not when the user types (inside the input or inside the text box).

$(window).keydown(function (evt) { if (evt.which == 46) { // delete goDoSomething(); } }); 

Any ideas how I can amend the above to not fire if the user is in a input or textarea ?

Thanks in advance,

Dave

+7
source share
3 answers

check type evt.target:

 $(window).keydown(function (evt) { if (evt.target.tagName.toLowerCase() !== 'input' && evt.target.tagName.toLowerCase() !== 'textarea' && evt.which == 46) { // delete goDoSomething(); } }); 
+14
source

You can have a global variable and set it to something when the text field is focused and reset it is blurred. Something like that:

 var textboxSelected = false; $(":input").focus(function () { textboxSelected = true; }); $(":input").blur(function () { textboxSelected = false; }); 

Then, in your onKeyDown event, check if the variable is set to false before executing the remaining functionality:

 $(window).keydown(function (evt) { if (evt.which == 46 && textboxSelected == false) { goDoSomething(); } }); 
0
source

try the following:

 $(window).keydown(function (evt) { if(evt.target != $('input') && evt.target != $('textarea')){ if (evt.which == 46) { // delete goDoSomething(); } } }); 
0
source

All Articles