jQuery and ASP.NET

February 25, 2009

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.

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Disable a Button if non numeric characters are entered"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions