Allow only numeric input using jquery

Hi! I’m really in the mood to add up some stuff in my blog. So here I am again. Expect that there will be more quick tutorials like this since I’ll be working on a project, a website to be exact. I can’t really afford to do some in-depth tutorials so I’ll just do it like this.

Okay, enough with the quick update of my life. This time, I’m going to show you how you can control what kind of input goes to your text fields using jquery.

 

Requirements

 


Procedure

You can actually view the source of this demo and get your way through it. But if you cannot make it work then you can continue reading.

First, you have to include both the jquery core and jquery numeric plugin in your file:

<script type="text/javascript" src="../../js/jq.js"></script>
<script type="text/javascript" src="../../js/numeric/jqnumeric.js"></script>

The actual link might not look like that. I’m assuming that you already know how to link files. If not then you can take up a course at w3schools.com on css, or javascript.

Third, add up the script that will make use of the javascript file which you included earlier.

<script type="text/javascript">
    
    $(".numeric").numeric();
    $(".integer").numeric(false, function() { alert("Integers only"); this.value = ""; this.focus(); });
    $(".positive").numeric({ negative: false }, function() { alert("No negative values"); this.value = ""; this.focus(); });
    $(".positive-integer").numeric({ decimal: false, negative: false }, function() { alert("Positive integers only"); this.value = ""; this.focus(); });
    
</script>

The code is pretty much self-explanatory. The 2nd line says that any text input element (textfield, textarea) that has an attribute of class which is equal to numeric will be affected by the script which only lets you to input numbers on a text field. The following lines does the same thing but with a different flavor.

 

Conclusion

That’s it for this quick tutorial. I hope you learned something, thanks for reading!

3 thoughts on “Allow only numeric input using jquery

  1. you can’t make use of the jquery numeric plugin if you want something like that, what you could do is to check the key code for 0-9 and key code for – and +
    something like the one below, I haven’t actually tried the code below let me know if it doesn’t work so I can tweak it.
    var allowed_keycodes = []; //research on the keycodes and place them inside the array
    $(‘.numeric’).keydown(function(e){
    if(x.indexOf(e.keyCode) != -1){
    //allowed
    }
    });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s