I have the following validation to allow only numbers and a decimal in Javascript
function validate(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();
}
}
I call this in my textbox element like onkeypress='validate(event)'
This code works fine in IE but when I try the same with Firefox backspace, left and right arrow keys and space does not work.
How would I fix this?
Using key press is the right solution, but you simply need to attach the event handler by JS (which is considered better practice anyway), and use something like this: