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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: