Select2 to display optgroup value and concatenated option

1

I'm creating a selection field where the user can choose between several states, but I need to show when I select both the value of the optgroup and the option,

Remembering that I'm using library select2

follows the base html

<select name="estados[]" id="estados" multiple  style="width:300px">
    <optgroup label="Suldeste">
        <option value="SP">São Paulo</option>
        <option value="RJ">Rio de Janeiro</option>
        <option value="MG">Minas Gerais</option>
        <option value="ES">Espírito Santo</option>
    </optgroup>
    <optgroup label="Sul">
        <option value="PR">Paraná</option>
        <option value="SC">Santa Catarina</option>
        <option value="RS">Rio Grande do Sul</option>
    </optgroup>
    <optgroup label="Nordeste">
        <option value="AL">Alagoas</option>
        <option value="BA">Bahia</option>
        <option value="CE">Ceará</option>
        <option value="MA">Maranhão</option>
        <option value="PB">Paraíba</option>
        <option value="PE">Pernambuco</option>
        <option value="PI">Piauí</option>
        <option value="RN">Rio Grande do Norte</option>
        <option value="SE">Sergipe</option>
    </optgroup>
    <optgroup label="Centro-Oeste">
        <option value="DF">Distrito Federal</option>
        <option value="GO">Goiás</option>
        <option value="MT">Mato Grosso</option>
        <option value="MS">Mato Grosso do Sul</option>
    </optgroup>
    <optgroup label="Norte">
        <option value="AM">Amazonas</option>
        <option value="AC">Acre</option>
        <option value="RR">Roraima</option>
        <option value="RO">Rondônia</option>
        <option value="AP">Amapá</option>
        <option value="PA">Pará</option>
        <option value="TO">Tocantins</option>
    </optgroup>
</select>

and the js call to select2 works

$("#estados").select2();

Follow an example on jsfiddle

Notice that when you choose a state it shows the name of the state, but you would need it to show both the region and the state, for example, Southeast.

    
asked by anonymous 11.02.2016 / 22:11

1 answer

1

Here in this response of So-English addresses your issue, specifically in this jsfiddle that I found to be the best but only works with simple selection.

With the help of the Question Author in jsFiddle and with that question in So-English we adapted the code to work for multiple select;

Add:

function format(item) {

      var el = item.element;        
    var og = $(el).closest('optgroup').attr('label');    
    return og+'-'+item.text;
}

$("#estados").select2({
    formatSelection: format,
    escapeMarkup: function(m) { return m; }
});
    
12.02.2016 / 00:17