Disable Backspace and Delete key with JavaScript | Example code

Use onkeydown event and preventDefault() method to Disable Backspace and Delete key in JavaScript. Backspace char code is 8 and delete key char code is 46.

Example Disable backspace and delete key with JavaScript

HTML example code.

Full browser window disabled keys

Prevent the event’s default action of back space and delete key.

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="myInput">

  <script>

    window.onkeydown = function (event) {

      if (event.which == 8 || event.which == 46) { 

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

         alert(event.code);
       } };      
     </script>

</body>
</html>

In input filed blocked backspace and delete key

Using id to get element. This code will disable only input field back and delete button,

<!DOCTYPE html>
<html>
<body>

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

  <script>

    var input = document.getElementById('myInput');
    
    input.onkeydown = function (event) {

      if (event.which == 8 || event.which == 46) { 

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

         alert(event.code);
       } };      
     </script>

</body>
</html>

Output:

Disable Backspace and Delete key with JavaScript

Do comment if you have any another example or doubts on this JS keycode topic.

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.