Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.toLowerCase();
    if (element != 'input' && element != 'textarea') {
        if (e.keyCode === 8) {
            return false;
        }
    }
});
like image 735
Jeremy Avatar asked Apr 14 '10 18:04

Jeremy


2 Answers

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.

like image 91
SLaks Avatar answered Oct 16 '22 20:10

SLaks


try this code:

$("*:not(input)")
like image 42
Nguyen Minh Binh Avatar answered Oct 16 '22 20:10

Nguyen Minh Binh