I'm having trouble using the Select2 with various groups, only the latter appears.
<select name="txtConta" id="txtConta" data-placeholder="Selecione a conta">
<option value=""></option>
<option value="S11892">2 - Gastos</option>
<option value="S11893">2.1 - DESPESA OPERACIONAL FIXA</option>
<option value="S11895">2.1.1 - PESSOAL</option>
<option value="S11915">2.1.1.1 - GERENCIA/ADMINSTRATIVO</option>
<option value="11916">2.1.1.1.1 - SALÁRIOS</option>
<option value="11917">2.1.1.1.2 - DIVIDENDOS / COMISSÕES /BONUS</option>
<option value="11918">2.1.1.1.3 - INSS</option>
<option value="11919">2.1.1.1.4 - FGTS</option>
<option value="11920">2.1.1.1.5 - IRRF COD. 0561</option>
<option value="11921">2.1.1.1.6 - PLANO DE SAUDE</option>
<option value="11922">2.1.1.1.7 - TICKET REFEICAO</option>
<option value="11923">2.1.1.1.8 - VALE TRANSPORTE</option>
(...)
</select>
<script>
$('select').each(function () {
$(this).select2({
allowClear: true,
width: 'resolve',
dropdownAutoWidth: true
});
});
$('#txtConta').find('option').each(function () {
if ($(this).attr("value").indexOf('S') == 0) {
$('<optGroup/>').attr('label', $(this).text()).appendTo($('#txtConta'));
$(this).remove();
} else {
$('#txtConta').find('optGroup').last().append($(this));
}
});
</script>
You can see a demonstration in this jsfiddle.