jQuery and ASP.NET

May 30, 2010

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



'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

2 Responses to "Using the jQuery Validation Plugin to choose atleast one CheckBox before submitting the Form"
  1. Anonymous said...
    March 16, 2011 12:43 AM

    Did u know how to make this work with multiple select? like:

    bev[ ]

    ?

  2. alexkwatson said...
    March 25, 2011 7:04 AM

    Yes, you just put 'bev[]' (single quotes included) instead of bev in the validate function.

 

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