Reputation: 1429
I created a select element, set to allow multiple selection and integrated chosen plugin with optgroups like below:
<select id="attributes" name="data[attributes]" multiple>
<optgroup label="Color" class="max_one">
<option value="Black">Black</option>
<option value="Yellow">Yellow<option>
<option value="Red">Red</option>
</optgroup>
<optgroup label="Year">
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
</optgroup>
<optgroup label="Top Speed" class="max_one">
<option value="120">120m/h</option>
<option value="140">140m/h</option>
<option value="160">160m/h</option>
</optgroup>
</select>
The user can select multiple values from each optgroup obviously.
I want to add a method to jquery validation and make sure, that at least and only 1 option is selected from each optgroup with class .max_one, using jquery validation.
I have tried the require_from_group: [1, ".max_one"] function but it only works with plain checkboxes.
Upvotes: 0
Views: 1053
Reputation: 98738
require_from_group
has nothing specific to do with checkbox elements. It works on a "group" of input elements. input
, select
or textarea
are the only valid elements.
However, in your case, there is only ONE input element... a single select
. And since option
elements are children of a select
element, they are not validated on their own.
In other words, the require_from_group
method is not going to recognize option
or optgroup
elements as input elements; only the parent select
as a single input.
Upvotes: 0
Reputation: 2142
@Sparky said it was out of the capabilities of jquery-validate, but maybe something like this will help you.
$('#attributes').on('change', function () {
$('.max_one').each(function () {
$('option').each(function () {
if ($('option:selected').length == 1) {
// Valid
} else {
// Invalid
}
});
});
});
Upvotes: 1