I am using Select2 and trying to allow the user to select one or more values from the drop-down list. Each value has an attribute data-select2-id, which does not allow to do it like this - stackowerflow - q/36505197/4822490. And even when you select a value, it is not deleted from select, but remains, but if you select it again, the selected value is reset. Selected items have a select2-selection__choice class, a title attribute, and data-select2-id. Any ideas, maybe someone came across, I will be very grateful.
If I understand correctly, you have a multiple-select Select2, and instead of Select2’s default behavior for multi-select (which is to display a “tag” for each selected item and to remove the selected item from the dropdown), you want the selected items to remain visible in the dropdown (probably highlighted in some way) and allow the user to click again to deselect an item.
There is no way to configure a standard Select2 to do this. However, you could provide that functionality yourself by supplying your own implementations of the SelectionAdapter and ResultsAdapter. Unfortunately, apart from studying the default implementations of those adapters (the implementations that ship with Select2), there isn’t much documentation on how to write your own implementations. But you can find the default implementations on the Select2 GitHub site, if this is something you want to pursue.
Thank you. You help me wery match.
Hello, I found solution. This solution is not the best, but it work’s. Sorry for my bad English!
$("#periodos").on("select2:select",function(e){
e.preventDefault();
let limite_periodos = $("#schemas").val().length;
var element = e.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
$("#periodos").append('<option value="'+e.params.data.text+'">' +e.params.data.text + '</option>');
$('#periodos').trigger('select2:close');
return true;
});
$('#periodos').on('select2:unselect',function(event){
var detect = false;
var element = event.params.data.text;
var selections = $('#periodos').select2('data');
var el = event.params.data.element;
var $el = $(el);
$el.detach();
});
$('#periodos').on('select2:close',function(event){
var select = document.getElementById("periodos");
var options = [];
document.querySelectorAll('#periodos > option').forEach(
option => options.push(option)
);
while (select.firstChild) {
select.removeChild(select.firstChild);
}
options.sort((a, b) => parseInt(a.innerText)-parseInt(b.innerText));
for (var i in options) {
select.appendChild(options[i]);
}
});