geo*_*310 4 javascript jquery select2
我正在使用 jQuery 插件Select2
如果我有一个具有以下结构的多选:
<select name="search-term[]" multiple="multiple">
<optgroup label="Categories">
<option value="category_4">Internal</option>
<option value="category_2">Business</option>
<option value="category_5">External</option>
<option value="category_1">Science</option>
<option value="category_6">Sports and Social</option>
</optgroup>
<optgroup label="Event Types">
<option value="eventtype_2">Meeting</option>
<option value="eventtype_3">Social Activity</option>
<option value="eventtype_4">Sporting Activity</option>
<option value="eventtype_1">Symposium</option>
</optgroup>
<optgroup label="Locations">
<option value="location_2">Office 1</option>
<option value="location_3">Office 2</option>
<option value="location_1">Office 3</option>
</optgroup>
</select>
Run Code Online (Sandbox Code Playgroud)
如果我在标记为 Locations 的 optgroup 下选择“Office 1”,则所选选项上的标签显示“Office 1”
有没有办法更改它,以便它也显示 optgroup 标签,以便选择选项上的标签会显示“位置:Office 1”。
请参阅下图以了解我所指的标签:
我最后使用 templateSelection 选项对其进行了排序,如下所示:
$('select').select2({
templateSelection: function(item)
{
value = item.id;
select_name = item.element.offsetParent.name;
optgroup_label = $('select[name="'+ select_name +'"] option[value="'+ value +'"]').parent('optgroup').prop('label');
if(typeof optgroup_label != 'undefined') {
return optgroup_label+': ' + item.text;
} else {
return item.text;
}
}
});
Run Code Online (Sandbox Code Playgroud)