Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 279
geoffs3310 Avatar asked Mar 15 '16 17:03

geoffs3310


2 Answers

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;
        }
    }
});
like image 161
geoffs3310 Avatar answered Sep 18 '22 10:09

geoffs3310


I do a jsFiddle for you, see https://jsfiddle.net/vcwrjpny/

$('option').click(function() {
    alert($(this).parent('optgroup').attr('label'));
})

EDIT :

with plugin select2 :

Do like that : see here http://jsfiddle.net/bJxFR/68/

  function format(item) {
           opt = $('select').find(':selected');
           sel = opt.text();
           og = opt.closest('optgroup').attr('label');
           alert('your optgroup is : ' + og);
          return item.text;

    }
    $("select").select2({
    formatSelection: format,
    escapeMarkup: function(m) { return m; }
    });
like image 40
Greg Avatar answered Sep 19 '22 10:09

Greg