jQuery: keyPress Backspace won't fire?
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();
});