Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?
A safer approach is checking the value of the input, instead of hijacking keypresses and trying to filter keyCodes.
This way the user is free to use keyboard arrows, modifier keys, backspace, delete, use non standard keyboars, use mouse to paste, use drag and drop text, even use accessibility inputs.
The below script allows positive and negative numbers
1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed
var input = document.getElementById('number');
input.onkeyup = input.onchange = enforceFloat;
//enforce that only a float can be inputed
function enforceFloat() {
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if (!valid.test(this.value)) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
}
EDIT: I removed my old answer because I think it is antiquated now.