Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable the backspace key for anything inside <body> EXCEPT inputs and textareas, using jQuery?

I would like to disable the backspace key (keycode 8) for any element except textboxes and textareas.

Here is what I tried without success:

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

...

$("*:not(input, textarea)").keydown(function(event) {
    if (event.keyCode == 8) {
        event.preventDefault();
        return false;
    }
});

..

$("body").not("input,textarea").keydown(function(event) {
    if (event.keyCode == 8) {
        event.preventDefault();
        return false;
    }
});

The idea is to avoid the user to accidentally hit the backspace key while not focused in any textbox or textarea.

Any thoughts?

like image 888
Charles Morin Avatar asked Nov 23 '25 13:11

Charles Morin


1 Answers

You also want to disable for text areas or textboxes that are readonly.

If text areas or text boxes are readonly and have focus then hitting backspace will cause you to leave the page as well. That is why you should also check for readonly.

I'm assuming your trying to prevent back functionality.

EDIT:

You could also attach the listener to the body as well. EDIT2: you need to prevent action on checbox too (which is input)

$(document).keydown(function (e) {
                var element = e.target.nodeName.toLowerCase();
                if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly") || (e.target.getAttribute("type") ==="checkbox")) {
                    if (e.keyCode === 8) {
                        return false;
                    }
                }
});
like image 60
Mike Avatar answered Nov 25 '25 10:11

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!