You can capture a backspace key on the onkeydown event. Once you get the key of the pressed button, then match it with the Backspace key code. A Backspace key keycode it 8.
The keypress event is fired when a key is pressed down and that key normally produces a character value
Use keydown
instead of keypress
.
The keyboard events occur in this order: keydown
, keyup
, keypress
The problem with backspace probably is, that the browser will navigate back on keyup
and thus your page will not see the keypress
event.
Capture the backspace keypress event in JavaScript
HTML example code.
event.key === “Backspace“,
More recent and much cleaner: use event.key
with addEventListener. No more arbitrary number codes!
<!DOCTYPE html>
<html>
<body>
<input type="text" id="myInput" name="">
<script>
var input = document.getElementById('myInput');
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace") {
alert(key);
return false;
}
});
</script>
</body>
</html>
Output:
Detect backspace on “input” event
Backspace is not allowed in the input field.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="myInput" name="">
<script>
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8)
return false;
};
</script>
</body>
</html>
Q: JavaScript keypress backspace not working or not detecting?
Answer: Try “onkeydown” instead of “onkeypress“. KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.
Do comment if you have another example or doubts on this JS event code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
> Q: JavaScript keypress backspace not working or not detecting? Answer: Try “onkeydown” instead of “onkeypress“. KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.
Fixed my problem; keep up the work!