Disable a Button if non numeric characters are entered

Here's a scenario. You have to accept only numeric characters from the user in a textbox. If the user types in anything other than a numeric character, then the submit button should be disabled.

To achieve this requirement we can use JavaScript and the OnKeyUp event as shown below:

Script


<head runat="server">


<title></title>


<script type="text/javascript">


function CallScript(sender, btn) {


var chkDigit = /^\d+$/;


if (chkDigit.test(sender.value)) {


document.getElementById(btn).disabled = false;


}


else {


document.getElementById(btn).disabled = true;


}


}


</script>




</head>


<body>


<form id="form1" runat="server">


<div>


<asp:TextBox ID="TextBox1" runat="server"/>


<asp:Button ID="Button1" runat="server"


Text="Submit" Enabled="false" />


</div>


</form>


</body>


</html>




To register the OnKeyUp with the TextBox use the following code:

C#


protected void Page_Load(object sender, EventArgs e)


{


TextBox1.Attributes.Add("onKeyUp", "CallScript(this,'Button1')");


}






VB.NET


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


TextBox1.Attributes.Add("onKeyUp", "CallScript(this,'Button1')")


End Sub




If you are using this script in a MasterPage, make sure to use Button1.ClientID

Note: Watch for the Copy and Paste scenarios where you will need to use the TextChangedEvent.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: