How to allow only numeric input using jQuery

How to allow only numeric input using jQuery

Hello friends, welcome to my today’s post. Today I’m going to show you, How to allow only numeric input in text box using jQuery. Few days ago, I was working on a POS (Point of Sales ) project and needed a script that allows only numerical numbers input in text field as well as prevents all other alphabetic characters.

Reason was, if the user adds any alphabetic character into a money amount input field then it going to generate a mathematical issue in the software calculation. To avoid this kind of unwanted issue, we should not allow characters where the software requires only numeric inputs. So, I wrote the following jQuery script that allows only them numerical values terms in a input box.

– Allow only numbers :

$(function(){
    $("#amount_input").on("keydown",function(event){                    
        if(event.shiftKey)
            event.preventDefault();                    
        if (event.keyCode == 46 || event.keyCode == 8) {
         // Allow all numbers from 0 to 9
        } else {
            if (event.keyCode < 95) {                            
                if (event.keyCode < 48 || event.keyCode > 57) {
                    event.preventDefault();
                }
            } else {                            
                if (event.keyCode < 96 || event.keyCode > 105) {
                    event.preventDefault();
                }
            }
        }
    });
});

– Allow Any Decimal Numbers:

$(function(){
    $("#amount_input").on("keydown",function(event){                    
        if(event.shiftKey)
            event.preventDefault();                    
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190) {
         // Allow all decimal numbers from 0 to 9 with dot(.)
        } else {
            if (event.keyCode < 95) {                            
                if (event.keyCode < 48 || event.keyCode > 57) {
                    event.preventDefault();
                }
            } else {                            
                if (event.keyCode < 96 || event.keyCode > 105) {
                    event.preventDefault();
                }
            }
        }
    });
});

– Add A Simple HTML Input Box:

Money Amount: <input id="amount_input" value="" type="text">

As you can see, you just need to define an input field with an ID. Next, set this ID into the jQuery code block. In our example code, we defined an input field with and ID “amount_input”. Finally, set this ID into the jQuery script.

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top