STAT1C
STAT1C

Reputation: 23

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>

Upvotes: 1

Views: 1493

Answers (4)

Angelos Chalaris
Angelos Chalaris

Reputation: 6707

You should use the keyup instead of keypress event, as certain keys (such as backspace) will not cause that event to fire.

$(document).keyup(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>

Upvotes: 1

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

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

Upvotes: 1

void
void

Reputation: 36703

Use keyup instead of keypress to get all the key codes

$(document).keyup(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>

Upvotes: 0

Gorgamite
Gorgamite

Reputation: 237

The keypress event is only evoked on printable keys. To print any key, you'll want to use the onkeydown event. It's raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc. Read more about they onkeydown event here: https://api.jquery.com/keydown/ Here's an example of how it would turn out:

$(document).keydown(function(e) {

Upvotes: 0

Related Questions