Limit HTML Text Field To Numbers Only
Using JavaScript to limit which characters can be typed into an HTML input field is very easy. Let’s say you have a field that should only accept numbers in an HTML form. Simply attach an onkeydown event to the <input> element that checks for which key is being pressed. If the key is not valid then the function returns false and the character will not be printed.
document.getElementById(”code”).innerHTML = keyCode;
// Any number or a backspace/delete/tab
return (keyCode > 47 && keyCode 36 && keyCode 95 && keyCode
- The numbers zero through nine at the top of the keyboard are key codes 48 through 57.
- The numbers zero through nine on the keypad are key codes 96 through 105.
- Backspace has a key code of 8.
- The delete key has a code of 46.
- Tab’s key code is 9.
- The arrow keys are codes 37 through 40.
Posted: January 26th, 2006 under javascript.
Comments: none
Write a comment