Allow numbers/digits only in input box using Javascript

Sometimes we need users to enter only digits / numbers in the input fields (e.g in zip code field) in our forms.

In this article you will learn how to restrict any form input field to enter digits or numbers only using javascript.

Although this can be by passed in some cases, but it still controls alot of spam.

Please note, always check the input fields to confirm that they’re digits via server side script (php for example) once they’re submitted.

How to allow only numbers / digits in input field using javascript

Take a look at simple example:
<html>
<head>
<script language=Javascript>
<!--
function isNumber(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;

return true;
}
//-->
</script>
</head>
<body>
<form><input id="digitsonly" onkeypress="return isNumber(event)" type="text" name="digitsonly" /></form>
</body>
</html>

Now if you copy and save this code in a html file, you will see an input field which will accept digits only.

In this example, we’ve added a function to check if the entered number is a digit / number or some other character (alphabet or special character).

In the input field we added “onkeypress” attribute with a value to return the response of isNumber function which we created in javascript.

So whenever a key is pressed, this function is called and it checked if the entered character is a digit or number or not, if not then nothing is returned, which means nothing is added to the input box, however if it is a number / digit, then it is returned normally and the number gets added to the input box.

Try it out and let me know if you have any difficulty in implementing it.

Leave a Reply

Your email address will not be published.