CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Restrict Characters and Allow only Integers in Textbox using JavaScript
Submitted By Satheesh Babu B
On 11/25/2008 6:22:10 AM
Tags: CodeDigest,javascript  

 Restrict Characters and Allow only Integers in Textbox using JavaScript

 


Most often, we will do validation to allow only integer input in a texbox. For example, a textbox that takes age as input should have only integer values.

 

We will normally do this by allowing user to type the input and validate it when the user is submiting the page or on blur event of the textbox control. It will be better if we can restrict the users from typing any other characters other than integer values.


The following javascript code will help us achieving this in ASPX page.
 
function RestrictInt(val)
    {
    if(isNaN(val)){
    val = val.substring(0, val.length-1);
    document.form1.txtAge.value = val;
    return false;
    }
    return true;
    }
 
 
<asp:TextBox ID="txtAge" onKeyUp="javascript: return RestrictInt(this.value)" runat="server"></asp:TextBox>


The above code will call the javascript function RestrictInt() by passing the typed value as parameter for every key up event. This function will allow the character if it is a integer else it will clear it.

 
The above script will allow only integers to be typed in the textbox.

 

Happy Coding!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..