jQuery select2在选择时显示optgroup标签 [英] jQuery select2 show optgroup label when selected
问题描述
我正在使用jQuery插件 Select2
I am using the jQuery plugin Select2
如果我具有以下结构的多重选择:
If I have a multiselect with the following structure:
<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>
如果我在optgroup下选择了标签为Locations的"Office 1",则所选选项上的标签显示为"Office 1"
If I select "Office 1" under the optgroup labelled Locations then the label on the selected option says "Office 1"
是否可以更改此方法,使其也显示optgroup标签,因此选择选项上的标签将显示"Location:Office 1".
Is there a way to change this so that it shows the optgroup label as well so the label on the selection option would say "Location: Office 1".
请参见下图以获取我所指的标签:
See the following image for the label I am referring to:
推荐答案
我最终使用templateSelection选项将其排序,如下所示:
I sorted it in the end using the templateSelection option like so:
$('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;
}
}
});
这篇关于jQuery select2在选择时显示optgroup标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!