JQuery: How to select all elements except input and textarea? (to disable keydown event)
I am trying to disable the backspace key in my jQuery app, so that it does not cause the browser to go back a page. However, I do not want to disable it if an input or textarea element is focused, because I want backspace to work properly there.
So, I want to select anything that is not an input or textarea.
Here is the code. The problem is that it fires for every element, even inputs and textareas.
$(':not(input, textarea)').keydown(function(e) {
if (e.keyCode === 8) {
return false;
}
});
I do not understand why the :not() function is not working. Is there a better way I can do this?
Note that if I remove the :not() function, it works properly. That is, it only fires for input and textarea elements.
EDIT: Based on the accepted answer, here is code that works. I am sure there is a better way to do this.
$(document).keydown(function(e) {
var element = e.target.nodeName.t开发者_如何学编程oLowerCase();
if (element != 'input' && element != 'textarea') {
if (e.keyCode === 8) {
return false;
}
}
});
Your problem is that the keydown
event bubbles from the <input>
or <textarea>
element to the normal element that contains it, firing the event from that element.
You need to check e.target
.
try this code:
$("*:not(input)")
精彩评论