Skip to content

Allow the only Backspace and Delete in TextBox JavaScript | Example code

  • by

Use keydown block other key and Allow the only Backspace and Delete keys in TextBox JavaScript.

The keypress event is fired when a key is pressed down and that key normally produces a character value (use input instead)

Allow the only backspace and delete in textbox JavaScript Example

HTML example code. Input textbox has already text.

A function will allow only char code key 8 for backspace and 46 for delete.

<!DOCTYPE html>
<html>
<body>

  <script>

    function isValidKey(e)
    {
      var charCode = e.keyCode || e.which;
      console.log(e.code);
      
      if (charCode == 8 || charCode == 46){

        return true;
      }
      return false;
    }

  </script>

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

</body>
</html>

Output:

Allow the only Backspace and Delete in TextBox JavaScript

Do comment if you have any doubts or suggestions on this JS Textbox 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

Your email address will not be published. Required fields are marked *