Friday, December 5, 2008

Allow only numbers / digits in TextBox.

Allow only numbers/digits in TextBox. How to use Javascript to allow only numbers to be entered in a textbox. This is useful for phone numbers, ZipCode, and etc., Use the following two step to solve this situation. This solution works in both IE and Netscape/Mozilla.

Step 1: Add the following javascript into you page.

function AllowNumbersOnly(evt)
{
// Allow numbers only in the Textbox.
var e = event evt; // for trans-browser compatibility
var charCode = e.which e.keyCode;
if (charCode > 31 && (charCode < 48 charCode > 57))
return false;
return true;
}

Step 2: Add the keypress event into your textbox.

<INPUT id="txtChar" onkeypress="return AllowNumbersOnly(event)" type="text" name="txtChar">

In asp.net add your textbox control and use this code behind.

TextBox.Attributes.Add("onkeypress", "javascript:return AllowNumbersOnly(event);");

Use technology!!!