Select2 Demo
by Suhaib Janjua
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css">
<input type="hidden" id="fruitSelect" value="" style="width:300px;" /><br />
<br />
<button type="button" id="showValue">Show Value</button><br />
<br />
<div id="output">
</div>
JavaScript
var FRUIT_GROUPS = [{
id: '',
text: 'Citrus',
children: [{
id: 'c1',
text: 'Grapefruit'
},
{
id: 'c2',
text: 'Orange'
},
{
id: 'c3',
text: 'Lemon'
},
{
id: 'c4',
text: 'Lime'
}
]
},
{
id: '',
text: 'Other',
children: [{
id: 'o1',
text: 'Apple'
},
{
id: 'o2',
text: 'Mango'
},
{
id: 'o3',
text: 'Banana'
}
]
}
];
$('#fruitSelect').select2({
multiple: true,
placeholder: "Select fruits...",
data: FRUIT_GROUPS,
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
});
}
}).on('select2-selecting', function(e) {
var $select = $(this);
if (e.val == '') {
e.preventDefault();
$select.select2('data',...