JQuery: how to select all elements except input and textarea? (to disable the keydown event)

I am trying to disable the backspace key in my jQuery application so that it does not force the browser to return the page. However, I do not want to disable it if the input element or textarea is focused, because I want the backspace to work there correctly.

So, I want to select something that is not an input or text field.

Here is the code. The problem is that it fires for every element, even inputs and text fields.

$(':not(input, textarea)').keydown(function(e) { if (e.keyCode === 8) { return false; } }); 

I do not understand why the not () function does not work. Is there a better way to do this?

Please note that if I remove the: not () function, it works correctly. That is, it runs only for input and textarea elements.

EDIT: based on the accepted answer, here is the code that works. I am sure there is a better way to do this.

  $(document).keydown(function(e) { var element = e.target.nodeName.toLowerCase(); if (element != 'input' && element != 'textarea') { if (e.keyCode === 8) { return false; } } }); 
+4
source share
2 answers

Your problem is that the bubble has keydown bubbles from the <input> or <textarea> element to the normal element that contains it, raising an event from that element.

You need to check e.target .

+6
source

try this code:

 $("*:not(input)") 
+3
source

Source: https://habr.com/ru/post/1306959/


All Articles