JQuery: Keypress not working on first click
This is my code
$(currentClass).keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
The only problem is that every time I press a key for the first time, no matter the letter or number, it appears in my span text tag. However, the second time I press the letter key, the code works, it only accepts the number. I don't know what is wrong with this code the first time the keys are pressed.
+3
source to share
4 answers
This is what I used
if ($.inArray($event.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// 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;
}
// 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();
}
I was able to resolve the issue with this. If their suggestion doesn't work, try this.
+1
source to share