Reputation: 23
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
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
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>
Upvotes: 1
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
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