Using the jQuery Validation Plugin to choose atleast one CheckBox before submitting the Form

Let us see how to use the jQuery Validation Plugin to choose atleast one checkbox before submitting the form

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<
head>
<
style type="text/css">
label.error {
float: none; color: red;
padding-left: .3em; vertical-align: top;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>

<
script type="text/javascript">
$.validator.addMethod('onecheck', function(value, ele) {
return $("input:checked").length >= 1;
}, 'Please Select Atleast One CheckBox')

$(document).ready(function() {
$("#form1").validate({
rules: {
bev: {
onecheck: true
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
}
});
});
</script>
<
title></title>
</
head>
<
body>
<
form id="form1">
<
div id="chkboxes">
<
input type="checkbox" name="bev" value="cream" />With cream<br />
<
input type="checkbox" name="bev" value="sugar" />With sugar<br />
<
input type="checkbox" name="bev" value="sugar" />With sugar<br />
</
div>
<
div id="err"></div>
<
input id="btnSubmit" type="submit" value="submit" />
</
form>
</
body>
</
html>

When the user tries to submit the form without selecting a checkbox, the validation fires and the following error message gets displayed

Select atlease one checkbox

The error disappears when a checkbox is selected and the user can now submit the form

This entry was posted in ASP.Net, jQuery, Syndicated. Bookmark the permalink.

Comments are closed.