Skip to content

JavaScript detect backspace and delete | example code

  • by

Using keydown event and addEventListener you can detect the key, whether it is back or del in JavaScript.

I Will check on the document property, you can also do it with the input filed. Using switch statement for matching conditions.

HTML example code with vanilla JavaScript.

<!DOCTYPE html>
<html>
<body>

  <script>

    document.addEventListener("keydown", KeyCheck);  //or however you are calling your method
    function KeyCheck(event)
    {
     var KeyID = event.keyCode;
     switch(KeyID)
     {
      case 8:
      alert("backspace");
      break; 
      case 46:
      alert("delete");
      break;
      default:
      break;
    }
  }
</script>
</body>
</html>

Output:

JavaScript detect backspace and delete

event.key === “Backspace” or “Delete”

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Do comment if you have any doubts or 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

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