Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Accept only numbers in a text field (See related posts)

Check user's input and allow numbers only (allowed characters list could be changed in the source).
The second parameter of "numbersonly" function allow to define if decimal numbers are allowed.

JavaScript code:
function numbersonly(e, decimal) {
var key;
var keychar;

if (window.event) {
   key = window.event.keyCode;
}
else if (e) {
   key = e.which;
}
else {
   return true;
}
keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
   return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
   return true;
}
else if (decimal && (keychar == ".")) { 
  return true;
}
else
   return false;
}


HTML code:
<form>
  <input name="number"  onKeyPress="return numbersonly(event, false)">
</form>

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts