I have a multiple select element with select2 v 3.5.2 plugin.
I need to be sure that the specific option value -1
will be not selected with other values.
I tried this solution:
$('#mysel').on("change",function(e){
if($("#mysel option[value=-1]").is(":selected") && $("#mysel option[value!=-1]:selected").length>0){
$("#mysel").val(-1).trigger('change.select2');
}
});
But it doesn't work, it change the value in html but select2 container is not updated. I also tried to switch the trigger to .trigger('change')
but it didn't work.
I tried to run a change with a setTimeout()
and it works... so I guess there is an issue on the event triggering the same event. Is there a solution other than not-so-elegant setTimeout update?
Instead of change
event use select2-close
event. You don't have to use the setTimeout
here. Try the below snippet.
$("#mysel").select2();
$("#mysel").on("select2-close", function (e) {
if($("#mysel option[value=-1]").is(":selected") && $("#mysel option[value!=-1]:selected").length>0){
let values = $("#mysel").val().filter(value => value != -1);
$("#mysel").val(values).trigger('change');
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>
<select multiple id="mysel" style="width:300px">
<option value="-1">None</option>
<option value="AL">Alabama</option>
<option value="Az">Arizona</option>
<option value="Ca">California</option>
<option value="Co">Colorado</option>
<option value="Fl">Florida</option>
</select>
Note that in the recent versions of the library, the event name select2-close
has been renamed to select2:close
.