I have an text box and applied Allow Alphabets With Space only using jquery. Its working in chrome But in firefox the backspace key is not working.
<input type="text" placeholder="" id="id1">
$(function(){
$('#id1').keypress(function (event) {
if ((event.which >= 65 && event.which < 91) || (event.which > 96 && event.which < 123) || event.which === 32 || event.which===0) {
return true;
}
else {
event.preventDefault();
}
})});
Here it is Plnkr
It is a difference in how the browsers handle the backspace character. In Chrome, backspace never makes it to the keypress event handler, but in Firefox it does.
If you add || event.which === 8
to your conditional, you'll allow backspace and return true, which will get it working in Firefox.
EDIT: Arrow Up, Down,Left, Right and Tab also doesn't work in firefox.
var ignoredKeys = [8, 9, 37, 38, 39, 40];
if (ignoredKeys.indexOf(event.which) >=0 || (event.which >= 65 && event.which < 91) || (event.which > 96 && event.which < 123) || event.which === 32 || event.which===0) {
return true;
} else {
event.preventDefault();
}
This should work in all [major] browsers:
$('#id1').keydown(function (event) {
if (event.which == 8) {
// ...
} else {
event.preventDefault();
}
);
Note the use of keydown
instead of keypress
, which is essential for it to work.
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