help with jquery validate plugin and checkboxes
I have a checkbox group that I need to name uniquely to store values in a database separately. However, using jquery validate plugin, I cannot validate the group with names being different.
<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 kin开发者_JS百科da works but it shows 2 error messages. One for each of the matching class 'competecheckbox'.
The problem is that even if the user selects compete1, the validation error message still remains for compete2.
How can I clear both messages when the user selects at least one checkbox?
thanks
I ended up with 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 :)
The validation rule would 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
I would use the groups
option for this. This option allows you to group whatever input
s 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
is used to determine if the message is one of the grouped fields. If it is, the error is inserted after the "yes" checkbox (this is easily changeable). Otherwise, it takes its default position after the element.- The
groups
option is used to specify a group namedcompetecheckbox
which includescompete1
andcompete2
. These two fields are validated together.
精彩评论