geoffs3310 geoffs3310 - 3 months ago 46
Javascript Question

jQuery select2 show optgroup label when selected

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>


If I select "Office 1" under the optgroup labelled Locations then the label on the selected option says "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:

enter image description here

Answer

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;
        }
    }
});