Search code examples
javascriptjqueryevent-handlingkeycodejquery-events

JavaScript Backspace Keycode doesn't work


The Keycode for the Backspace just doesn't work I tried it in IE and Google Chrome and it doesn't display anything neither in the console nor the alert Code:

$(document).keypress(function(e) {
  console.log(e.which);
  if (e.which == 13) {
    window.alert("enter");
  } else if (e.which == 8) {
    window.alert("backspace");
  } else {
    $("#prompt").append(String.fromCharCode(e.which));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Solution

  • keyPress event is invoked only for character (printable) keys, keyDown event is raised for all including nonprintable

    $(document).keydown(function(e) {
      console.log(e.which);
      if (e.which == 13) {
        window.alert("enter");
      } else if (e.which == 8) {
        window.alert("backspace");
      } else {
        $("#prompt").append(String.fromCharCode(e.which));
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    References