1
I’m creating a selection field where the user can choose between multiple states, but I need to show when selected both the optgroup value and the option value, have as?
Remembering that I am using the 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 for Select2 to work
$("#estados").select2();
follows an example in jsfiddle
realize that when choosing a state it shows the name of the state, but would need to show both the region and the state, for example, Suldeste - São Paulo.
Oops, I took a look and I’m sure you can help me, but there’s something strange that happens when I select a first option, it appears as Undefined the value of the optgroup label, do you have any idea? give a look at this updated http://jsfiddle.net/pb8b7f2b/1/ http:/jsfiddle.net
– Marcelo Diniz
@Marcelodiniz has to be multiple selection?
– Marconi
In this case yes, it may be that the end user chooses an option or more.
– Marcelo Diniz
And if you notice, if you choose a second option or even more other options it always returns the first label of optgroup
– Marcelo Diniz
@Marcelodiniz understood, this code does not work correctly with multiple selection.
– Marconi
give a look at this one http://jsfiddle.net/pb8b7f2b/3/ dai update your answer so I mark it as valid, after all it was with your help
– Marcelo Diniz
@Marcelodiniz It was top. If you want to edit you can be excited. I was trying with a friend at lunch, but I was fucking solve. Good that I could help.
– Marconi
@Marcelodiniz had even asked in the So-English. Look there. http://stackoverflow.com/questions/35361197/optgroup-value-multiple-select-with-selected2/35369650#35369650
– Marconi