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.
Last few days ago, I'd worked in a accounting software project and I need a script that only allow numerical numbers in text input box and prevent to input any alphabetic characters in our invoice input box.
You know, if you add any kind of alphabetic character in to a money amount input box then it will create a logical issue in your software calculation. To avoid this kind of unwanted issues we should not allow characters where software expect numeric input and need to restrict them. That's why we need to be more careful on this issue that user will never insert any alphabetic character in currency input filed. Finally I'd wrote a very simple jQuery script that allow only insert numeric terms in a input box.
So, lets have a look on source code.
$(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();
}
}
}
});
});
$(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();
}
}
}
});
});
Money Amount:
You can see that, you just need to define an input field ID and set this ID in your jQuery code block. As for example, here I wrote an ID for an input box called "amount_input" and then set this ID in to our jQuery script and we are done. That's all.
So, what do you think? Isn't it simple or too hard?
I've also added download and demo URL for you. So that, you can check script action in live. Enjoy!
- Create Image Blink with Fade In Effect in jQuery.
- 5 most wanted jQuery snippet for web developers.
- How to create a fading effect jQuery plugins.
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!
You might also like...
11+ Attractive jQuery Plugins For Mobile website
TubePlayer A YouTube Player jQuery Plugins
Md Mahbub Alam Khan is the Editor and Founder of CoolAJAX Web Blog. You can follow CoolAJAX on Twitter , on Facebook or you can subscribe via RSS .
Topics