471,066 Members | 1,609 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 471,066 developers and data experts.

How to validate for numbers only in textbox using Javascript

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
0 6942

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by c.verma | last post: by
2 posts views Thread by rockdale | last post: by
4 posts views Thread by mantrid | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.