Allow only numberic key presses.


/ Published in: JavaScript
Save to your folder(s)

The following code allows only numeric characters to be entered.


Copy this code and paste it in your HTML
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function checkIt(evt) {
  5. evt = (evt) ? evt : window.event
  6. var charCode = (evt.which) ? evt.which : evt.keyCode
  7. if (charCode > 31 && (charCode < 48 || charCode > 57)) {
  8. document.getElementById("errorMessage").innerHTML = "This field accepts numbers only."
  9. return false
  10. }
  11. document.getElementById("errorMessage").innerHTML = ""
  12. return true
  13. }
  14. </script>
  15. </head>
  16. <body>
  17. <input id="numbersOnly" type="text" onKeyPress="return checkIt(event)" />
  18. <span id="errorMessage"></span>
  19. </body>
  20. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.