How to Prevent Backspace key in JavaScript | Example code

Backspace key char is 8 and key is “Backspace”. Use onkeydown event and e.preventDefault() to disable backspace key.

Prevent Backspace key in JavaScript Example

HTML example code:

<!DOCTYPE html>
<html>
<body>

  <input type="text" id="myInput">
  <script>

    window.onkeydown = function (event) {

      if (event.which == 8) { 

         event.preventDefault();   // turn off browser transition to the previous page 

         alert("NOT ALLOWED");
       } };      
     </script>

</body>
</html>

Output:

How to Prevent Backspace key in JavaScript

Do comment if you have any doubts and suggestions on this JS code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.