jQuery and ASP.NET

September 24, 2009

Make Sure atleast One CheckBox is checked before submitting the Form - jQuery




Here’s a simple way to keep a required checkbox on the form and prevent the user from submitting a form, if one of the checkboxes is not checked:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Make Sure Atleast One CheckBox is Checked</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('input[id$=btnSubmit]').click(function(e) {
var checked = $(':checkbox:checked').length;
if (checked == 0) {
alert('Atleast One CheckBox Should Be Selected');
e.preventDefault();
}
});
});
</script>
</
head>
<
body>
<
input id="cb1" type="checkbox" value="1"/> Option One
<input id="cb2" type="checkbox" value="2"/> Option Two
<input id="cb3" type="checkbox" value="3"/> Option Three
<input id="btnSubmit" type="submit" value="Submit" />

</
body>
</
html>


To do this with ASP.NET controls in an ASP.NET application, the jQuery code remains the same. Just replace the following html controls with server controls:

<body>
<
form id="form1" runat="server">
<
div>
<
asp:CheckBox ID="cb1" runat="server" Text="Option One" /><br />
<
asp:CheckBox ID="cb2" runat="server" Text="Option Two" /><br />
<
asp:CheckBox ID="cb3" runat="server" Text="Option Three" /><br />
<
asp:Button ID="btnSubmit" runat="server" Text="Submit" />

</
div>
</
form>
</
body>

When the user tries to submit the form without checking any of the checkboxes, he/she gets an alert as shown below:

image

See a Live Demo



'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 "Make Sure atleast One CheckBox is checked before submitting the Form - jQuery"
 

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