I've an input box that I only want to allow letters, hyphen, space and backspace. All is good on chrome but on Firefox backspace (or charcode 8) does not work. - /
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) return false;
});
});
I've tried adding && (key.charCode != 8)
also changes keypress to others like 'keydown, keyup' etc...
Can anybody get this working in Firefox (40.0.3) or something that I can use instead?
I've an input box that I only want to allow letters, hyphen, space and backspace. All is good on chrome but on Firefox backspace (or charcode 8) does not work. - https://jsfiddle/npo7y7fr/
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) return false;
});
});
I've tried adding && (key.charCode != 8)
also changes keypress to others like 'keydown, keyup' etc...
Can anybody get this working in Firefox (40.0.3) or something that I can use instead?
Share Improve this question asked Oct 6, 2015 at 14:14 Tom RudgeTom Rudge 3,2729 gold badges55 silver badges103 bronze badges3 Answers
Reset to default 4Since Space will send keycode 32 and backspace will send 0 in Mozilla so that's why it is not working in mozilla.
change your script as below
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45) && (key.charCode != 32) && (key.charCode != 0) ) return false;
});
});
hope this helps..!!
Instead of hardcoding some special keys, just skip the filtering for all of them. With the accepted solution, you still cancel arrow keys, Home, End, etc., which is a bad thing for the user.
As all special keys have a key
field longer than 1 character, you can safely do this:
$(document).ready(function () {
$('.textInput').keypress(function (event) {
return event.key.length > 1 || event.ctrlKey || !!event.key.match(/[a-zA-Z \-]/);
});
});
The pressed key is accepted if it's a special key, it's been pressed simultaneously with the Ctrl key (to allow copying and pasting) or if it matches the regular expression (letters, space and hyphen).
As the user can paste invalid content, you should still remove illegal characters with the oninput
event (probably something like ctrl.value.replace(/[^a-zA-Z \-]+/g, '')
).
Rather than trying to control what the browser can enter into the input, it might be easier to just filter the contents of the textbox on keyup.
Consider the following:
$('.textInput').keyup(function() {
$(this).val( $(this).val().replace(/[^a-zA-Z]/,''));
});
Hope this helps.