.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> JQuery >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Accept only numeric and decimal values in TextBox using JQuery

Posted By:JQuery Developer       Posted Date: May 17, 2013    Points: 40    Category: JQuery    URL: http://www.dotnetspark.com  

JQuery code to allow user to enter only numbers or decimal values. this will work with all input (user enter) controls like textbox etc
 

If you want to restrict user to enter alphanumeric value and want user to only enter numeric or decimal value below is the JQuery code you can use. Below code also allow backspace.

Note: if you dont want decimal value please remove this code from if condiction keyCode != 190

JQuery Code

 <script type="text/javascript">

        $(document).ready(function () {
            $('input[name="number"]').keydown(function (e) {

                var keyCode = e.which; // Capture the event

                //190 is the key code of decimal if you dont want decimals remove this condition keyCode != 190
                if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
                    if (keyCode < 48) {
                        e.preventDefault();
                    }
                    else if (keyCode > 57 && keyCode < 96) {
                        e.preventDefault();
                    }
                    else if (keyCode > 105) { 
                        e.preventDefault();
                    }
                }
            });
        });
        
</script>

html texbox code

<input type="text" name="number" value=" " />

Click here for live demo code

For key code for any other key in case you want to restrict you can refer this website

http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.htmlv


     

Further Readings:

Responses
Author: Dorababu         Company URL: http://www.dotnetspark.com
Posted Date: December 06, 2013

It is accepting multiple decimal points, which is not a valid decimal, 1.......2..

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend