Help with jquery validate plugin and checkboxes

I have a group of checkboxes that I need to specify uniquely to store the values ​​in the database separately. However, using the jquery validate plugin, I cannot check a group with different names.

<label>Would you like to compete?</label> <input type="checkbox" name="compete1" value="2" class="competecheckbox" > <label for="compete_no">No</label> <input type="checkbox" name="compete2" value="1" class="competecheckbox"> <label for="compete_yes">Yes</label> <div id="competeyes"> <label class="competeyestxt" hidden=true>Which Location?</label> <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true"> </textarea> </div> 

I tried adding

 $.validator.addClassRules( "competecheckbox", {required: true, minlength: 1}); 

This view works, but it shows 2 error messages. One for each of the competing classes of the matching class.

The problem is that even if the user selects Compete1, the validation error message still remains for compet2.

How to clear both messages when the user selects at least one checkbox?

thanks

+4
source share
2 answers

I got something like this:

  <label>Would you like to compete?</label> <input type="checkbox" name="compete[]" value="2" class="competecheckbox" > <label for="compete_no">No</label> <input type="checkbox" name="compete[]" value="1" class="competecheckbox"> <label for="compete_yes">Yes</label> <div id="competeyes"> <label class="competeyestxt" hidden=true>Which Location?</label> <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true"> </textarea> </div> When the form is submitted you get values in an array as compete[1], compete[2] etc. I didn't know that you could do an empty array for form variable names. Every day I find out how ignorant I am :) 

Validation rule will look like

 $('#survey').validate( { rules: { "compete[]": { required: true, minlength: 1 } }); The quotes around "compete[]" are required as explained here: 

http://docs.jquery.com/Plugins/Validation/Reference#Fields_with_complex_names_.28brackets.2C_dots.29

+10
source

I would use the groups parameter for this. This option allows you to group all the input you want:

 $("#form").validate({ groups: { competecheckbox: "compete1 compete2" }, errorPlacement: function ($error, $element) { if ($element.attr("name") === "compete1" || $element.attr("name") === "compete2") { $error.insertAfter("label[for='compete_yes']"); } else { $error.insertAfter($element); } } }); 

Example: http://jsfiddle.net/z37Sj/


Notes:

  • errorPlacement used to determine if the message is one of the grouped fields. If so, the error is inserted after yes (this is easy to change). Otherwise, after the element, its default position is required.
  • The groups option is used to specify a group named competecheckbox , which includes compete1 and compete2 . These two fields are checked together.
+4
source

All Articles