Allow Only Numbers in Textbox using JQuery

In this post, we will learn about how to Allow Only Numbers in Textbox using JQuery with an example.

Description:

In my previous posts I have explained various topics like Read Connection string from web.configue, Why is Dictionary preferred over Hashtable, Introduction to BackboneJS, Bind an enumeration to combobox in WinForm, jQuery is undefined error: Common mistake every developer should avoid, 15 Powerful jQuery Tips and Tricks for Developers and Designer.

Now in this post, I will explain how to Allow Only Numbers in Textbox using JQuery with appropriate example. Many a times you want only numeric value in textbox like Count of something, Phone number ,Computer Port etc. In such a situation you can use Jquery to alllow only numeric value by writting below code.

First Of all add textbox control in  your html.

<input type="text" id="txtOnlyNumber" />

Now write below lines in JavaScript file or include it in script section of above html file.

 $(function () {
$('#txtOnlyNumber').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
e.preventDefault();
}
}
});
});

Read :

Summary

You can also read about ASP.NET, C#.Net, JQUERY, AJAX, JavaScript
I hope you get an idea about how to Allow Only Numbers in Textbox using JQuery .
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you liked this post, don’t forget to share this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website