Sometimes we need users to enter only digits / numbers in the input fields (e.g in zip code field) in our forms.
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.
Take a look at simple example:
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
<form><input id="digitsonly" onkeypress="return isNumber(event)" type="text" name="digitsonly" /></form>
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).
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.