Skip to content

Disable Backspace and Delete key with JavaScript | Example code

  • by

Use the onkeydown event and preventDefault() method to Disable Backspace and Delete key in JavaScript. Backspace char code is 8 and deletes 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 backspace 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 the element. This code will disable only the 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 other examples 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

Your email address will not be published.

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