How to disable backspace in textbox using JavaScript | Example code

Use onkeydown property and block key of backspace “8” or key “Backspace” to prevent users from using the backspace key in a textbox using JavaScript.

Note: This sounds creating a major usability issue if the user makes a typo.

Example disable backspace in textbox in JavaScript

HTML example code. Prevent backspace click via JavaScript by catching onKeyDown and returning false if ascii code is 8 (backspace).

<!DOCTYPE html>
<html>
<body>

  <script>
    function isValidKey(e)
    {
      var charCode = e.keyCode || e.which;
      if (charCode == 8){

        console.log(e.code);
        return false;
      }
      return true;
    }

  </script>

  <input id="tb_box" onkeydown="return isValidKey(event)" type="text" />

</body>
</html>

Output:

disable backspace in textbox using JavaScript

Do comment if you have any doubts and suggestion on this JS example 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.