By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,011 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to validate for numbers only in textbox using Javascript

P: n/a
Dhanisha K P
In ASP.NET you can use textboxes that can enter only numbers. For this, first you have to create a javascript file.

For creating a javascript file,
first right click on the Project name in Solution Explorer
Then,
select Add New Item -> JScript File-> Ok

If you want, you can give a name to JSCript file. Here I use the name "number.js". After that write the following code in that file.
Expand|Select|Wrap|Line Numbers
  1. function numberonly(e)
  2. {
  3.     var KeyID = (window.event) ? event.keyCode : e.which; 
  4.     if(KeyID>=48 && KeyID<=57)
  5.         return true;
  6.     else
  7.         alert("Please Enter Number Only");
  8.         return false;
  9.  }
  10.  

Save this file. Take the source part of the webform. Add the following code in <head> of html.
Expand|Select|Wrap|Line Numbers
  1. <head>
  2. <script type="text/javascript" src="number.js">
  3. </script>
  4. </head>

Take the source aspx.cs file. Inside the Page_Load function
write the below code.
Expand|Select|Wrap|Line Numbers
  1. TextBox1.Attributes.Add("onkeypress", "return numberonly(event);");

Where TextBox1 is the name of the TextBox where we want to enter the data.
Oct 14 '10 #1
Share this Article
Share on Google+