I have following javascript to prevent user from entering invalid characters into a text field. It's working well in chrome but not in firefox. It's preventing the backspace key to be entered in the text field in firefox.
function onlyNumbers(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Can anyone please have a look and propose a fix for firefox to not prevent backspace key to act on a text field ?
Probably I guess, adding the regex for the backspace character would do the job here. Does anyone know, how to add the regex for matching the backspace
Edit:
Also, the above code has supposed to interrupted with the Tab key behaviour, I am not able to jump to next fields in the form using Tab key.
see http://jsfiddle.net/8ZJZD/1/
Just use
if(key===8){return;}
Edit:
If you want to exclude more keys, use
See it here: http://jsfiddle.net/8ZJZD/2/
You can know the
keyCode
of each key usingalert(key)
(before
key = String.fromCharCode(key)
).You could also exclude
Im not sure of the backspace regex but this should work too
You might do away with bind and directly attach keyup
Fiddle - jsfiddle