Jquery Script Not Working to accept input numbers only

Issue

I have written my Jquery script to input number only for textbox.
Following is my html code :

<input type="text" name="mobile_number" id="mobile_number" maxlength="10" class="form-control input-md" placeholder="Mobile Number" required="required">

When I try to input some value it accepts both numbers and characters also.

My Jquery Script is :

$("#mobile_number").keydown(function(event) {

if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {

}
else {

    if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
        event.preventDefault(); 
    }   
 } });

Solution

Check that you have included any version of jquery, also write your code in $(document).ready() like,

$(function () {
    $("#mobile_number").keydown(function (event) {
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {

        } else {
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                event.preventDefault();
            }
        }
    });
});

Demo

Answered By – Rohan Kumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published