HTML5 restricting input characters
Use html5 pattern attribute for inputs:
<input type="text" pattern="\d*" title="Only digits" />
OR
Use html5 number type for input :
<input type="number" />
To slightly improve off of jonhopkins excellent answer, I added backspace and delete key acceptance like so:
function inputValidate(){
var e = event || window.event;
var key = e.keyCode || e.which;
if (((key>=48)&&(key<=57))||(key==8)||(key == 46)) { //allow backspace //and delete
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
}
}
The input textbox
<input type="text" onKeyDown="myFunction()" value="" />
JavaScript
function myFunction() {
var e = event || window.event; // get event object
var key = e.keyCode || e.which; // get key cross-browser
if (key < 48 || key > 57) { //if it is not a number ascii code
//Prevent default action, which is inserting character
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
}