Using The Jquery Validate Plugin To Check If One Or More Checkboxes (with Different Names) Are Selected
Ok, so I am implementing the jQuery validate plugin for a Drupal 7 site. The problem I am running into is that one part of the form generates multiple checkboxes with slightly diff
Solution 1:
You'll want to do these things:
- Create a group for your checkboxes
- Create a custom validation method to ensure at least one of them is checked
- Add rules to your rules object for each checkbox
- Customize the
errorPlacement
function to put your error in an appropriate place
This is the code for #2 (see here for how the selector works):
$.validator.addMethod("custom_checks", function(value, element) {
return $('#photo-node-form input[name^="field_themes[und]"]:checked').length > 0;
}, 'Please check one of these');
Here's the code for #1 and part of #3:
var tmpChecks = [], myRules = {
'field_first_name[und][0][value]': 'required',
'field_last_name[und][0][value]': 'required',
'field_email_address[und][0][email]': {
required: true,
email: true,
},
'field_product_type[und]': 'required',
'field_terms_and_conditions[und]': 'required'
};
$('#photo-node-form input[name^="field_themes[und]"]').each(function(){
tmpChecks.push(this.name); //This is the start of #1
myRules[$(this).attr("name")] = {
custom_checks: true
}; //#3
});
And for #4, add this to your validate object:
errorPlacement: function(error, element) {
if (element.attr("name").match(/^field_themes\[und\]/)){
$('#checkbox_errors').html(error);
} else {
error.insertAfter(element);
}
}
You end up calling validate like this:
$("#photo-node-form").validate({
rules: myRules,
groups: {
checks: tmpChecks.join(' ') //the rest of #1
},
errorPlacement: function(error, element) {
if (element.attr("name").match(/^field_themes\[und\]/)){
//I added this span after all the textboxes, you can figure this out in a more dynamic way if you prefer
$('#checkbox_errors').html(error);
} else {
error.insertAfter(element);
}
}
});
Here is a working example on a simpler form: http://jsfiddle.net/ryleyb/nUbGk/1/
Post a Comment for "Using The Jquery Validate Plugin To Check If One Or More Checkboxes (with Different Names) Are Selected"