What I intend to do is that when selecting one of the options, put the parent text (optgroup) and show me something like " LG / Lg - Test 1 " (notece in the example that I say that "LG" is the parent (optgroup) and "Lg - Test 1" is the child (option)) and I want to do so that the user can see which parent (optgroup) is selecting.
In the example that I put the function formatDataSelection
is the one that is responsible for placing the text when selecting an option.
Below the code of what I have:
var data = {"results":[{"text":"LG","children":[{"id":1,"text":"Lg - Prueba 1"},{"id":2,"text":"Lg - Prueba 2"}]},{"text":"Samsung","children":[{"id":3,"text":"Sam - Prueba 1"},{"id":4,"text":"Sam - Prueba 2"}]}],"pagination":{"more":false}};
$("select").select2({
placeholder: "Elija...",
allowClear: true,
data: data.results,
escapeMarkup: function (markup) { return markup; },
templateResult: formatData,
templateSelection: formatDataSelection
});
function formatData (data) {
if (data.loading) return data.text;
return data.text;
}
function formatDataSelection (data) {
return data.text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>
<select style="width: 100%"></select>
The response that the user @JuankGlezz gave me, led me to this other problem: The text of the parent label of the selected option is not available.
$('select').select2({
placeholder: "Elija...",
allowClear: true,
ajax: {
type: "GET",
dataType: 'json',
url: 'https://api.myjson.com/bins/12apr1',
delay: 250,
data: function(params) {
return {
term: params.term, // search term
page: params.page || 1, //page number
}
},
processResults: function (data, page) {
return {
results: $.map(data.results, function (n) {
return {
text: n.text,
children: n.children
}
}),
//results: data.results,
pagination: {
more: data.pagination.more,
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
templateResult: crear_marca_modelo_formatData,
templateSelection: crear_marca_modelo_formatDataSelection
});
function crear_marca_modelo_formatData (data) {
if (data.loading) return data.text;
return data.text;
}
function crear_marca_modelo_formatDataSelection (data) {
let labelOptg = $(data.element).parent().attr('label');
return labelOptg + " / " + data.text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>
<select style="width: 100%"></select>