Allow only numbers to be typed in a textbox HTML

Here we will see how to allow only numeric  or number to be types in any html textbox. This will be useful for phone number field, pincode or for only numeric authentication purpose.

To achieve this you could subscribe for the onkeypress event:

HTML TEXTBOX

<input type="text" class="textfield" value="" id="phone_number" name="phone_number" onkeypress="return hasNumber(event)" />

Now we need to define the hasNumber() function in javascript:

function hasNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

With HTML5 we can do this by only html attribute :

<input type="number" min="0">

 

 

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *