I'm using the jQuery Validation plugin with an HTML form for the first time. I'm used to using plain old javascript for this, but I totally love this plugin! Anyway, I'm stuck on trying to do some conditional validating.
The scenario: I have a two-part question in a form. The first part is a Yes/No dropdown (required). The second part is a group of checkboxes, which you must check at least one of them if you selected "Yes" in the previous dropdown.
<div>
<p><span class="bold large-font">8.</span> Some question to answer Yes or No to...</p>
<div class="margin-left-fifty">
<select id="Q8" class="Q8" name="Q8">
<option value="" selected></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
<div class="margin-left-fifty">
<p><span class="underline italic">If Yes,</span> indicate which areas...</p>
</div>
<div class="margin-left-eighty">
<input id="Q8yesA" class="Q8yes" name="Q8yesA" type="checkbox" value="Yes" />
<label for="Q8yesA"><span class="small-font">a.</span> Option A</label>
<br />
<input id="Q8yesB" class="Q8yes" name="Q8yesB" type="checkbox" value="Yes" />
<label for="Q8yesB"><span class="small-font">b.</span> Option B</label>
<br />
<input id="Q8yesC" class="Q8yes" name="Q8yesC" type="checkbox" value="Yes" />
<label for="Q8yesC"><span class="small-font">c.</span> Option C</label>
<br />
<input id="Q8yesD" class="Q8yes" name="Q8yesD" type="checkbox" value="Yes" />
<label for="Q8yesD"><span class="small-font">d.</span> Other</label>
<input name="Q8yesDlist" type="text" maxlength="255" size="50" value="" placeholder="Please list..." />
</div>
Note that is part of a rather large survey, so to make it easier and quicker to collate, I made each response an individual, rather than using an array.
I believe the code I'm using to validate the checkboxes is from here: validation for at least one checkbox
So right now, my function looks like this:
$(function(){
$.validator.addMethod('Q8yes', function (value) {
return $('.Q8yes:checked').size() > 0; }, 'Please check at least one box for Question 8.');
var checkboxes8 = $('.Q8yes');
var checkbox_names8 = $.map(checkboxes8, function(e,i) { return $(e).attr("name")}).join(" ");
$('#survey').validate({
groups: {
checks8: checkbox_names8
},
rules: {
Q8: "required",
},
messages: {
Q8: "Please answer Question 8.",
},
errorContainer: $('#errorContainer'),
errorLabelContainer: $('#errorContainer ul'),
wrapper: 'li'
});
});
I've been trying to wrap the addMethod in an If statement, but couldn't quite figure it out. I'm not even sure if that's the right idea.
You're help is greatly appreciated! Thanks!