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

No comments:

Post a Comment