I have used select2 to select multiple options from a drop down, but is it possible for select2 to select the full optgroup?? What I want is when user select the option grou
I've used John's code, but my problem was that I needed the ability to filter, so I added it. You can see the code working on jsfiddle.
This is the query code:
query: function (options) {
var selectedIds = options.element.select2('val');
var data = jQuery.extend(true, {}, FRUIT_GROUPS);
var selectableGroups = $.map(data, function (group) {
var areAllChildrenSelected = true,
parentMatchTerm = false,
anyChildMatchTerm = false;
if (group.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0) {
parentMatchTerm = true;
}
var i = group.children.length
while (i--) {
var child = group.children[i];
if (selectedIds.indexOf(child.id) < 0) {
areAllChildrenSelected = false;
};
if (options.term == '' || (child.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0)) {
anyChildMatchTerm = true;
}
else if (!parentMatchTerm) {
var index = group.children.indexOf(child);
if (index > -1) {
group.children.splice(index, 1);
};
};
};
return (!areAllChildrenSelected && (parentMatchTerm || anyChildMatchTerm)) ? group : null;
});
options.callback({ results: selectableGroups });
}
First give id to your select for example
<select style="width: 95%" id="selectgroup">
and then add class to your optgroup like
<optgroup value="ATZ" label="Alaskan/Hawaiian Time Zone" class="select2-result-selectable">
and then add this
$('#selectgroup').select2({
}).on('select2-selecting', function (e) {
debugger;
var $select = $(this);
if (e.val == undefined) {
e.preventDefault();
var childIds = $.map(e.choice.children, function (child) {
return child.id;
});
$select.select2('val', $select.select2('val').concat(childIds));
$select.select2('close');
}
});
If you click on optgroup then It will select all the options under the optgroup.