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.
Use keyup
instead of keypress
. This gets all the key codes when the user presses something
I came across this myself. I used .on
so it looks a bit different but I did this:
$('#element').on('keypress', function() {
//code to be executed
}).on('keydown', function(e) {
if (e.keyCode==8)
$('element').trigger('keypress');
});
Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery
$(this).bind("keydown", function (event) {
// Allow: backspace, delete
if (event.keyCode == 46 || event.keyCode == 8)
{
var tempField = $(this).attr('name');
var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
$('#' + hiddenID).val('');
$(this).val('')
return;
} // Allow: tab, escape, and enter
else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else
{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
{
event.preventDefault();
}
}
});
If you want to fire the event only on changes of your input use:
$('.s').bind('input', function(){
console.log("search!");
doSearch();
});
According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)
In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown
to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.
jQuery(el).keydown( function() {
var that = this; setTimeout( function(){
/** Code that processes backspace, etc. **/
}, 100 );
} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With