我正在使用select2 version4.0进行多重选择,因为从API调用加载值时我附加了'all'选项。当“所有”被选择其它选项应该是未选择的,当我选择任何其它的选项“所有”选项应该未被选择。
HTML:
<div class="form-group col-lg-6 field" >
<label for="exampleFormControlSelect2">Location</label>
<select class="form-control select2 select-etc-count" id="LOCATION" multiple="multiple" name="LOCATION[]">
<span class="select2-counts" style="display:none;"></span>
<span class="reset-link" style="display:none;" title=""> <i class="fa fa-refresh" onclick=""></i> </span>
</select>
JS:
$('#LOCATION').on("select2:select", function (event) {
selectId = $(this).attr("id");
value = $("#LOCATION").val();
console.log(selectId,value);
console.log("*********************");
if(jQuery.inArray("all", value) != -1) {
console.log("is in array");
var $select = $('#LOCATION');
var idToRemove = 'all';
var values = $select.val();
if (values) {
console.log("values->",values);
var i = values.indexOf(idToRemove);
console.log("I->",i);
if (i >= 0) {
console.log("coming");
values.splice(i, 1);
console.log("values after->",values);
$select.val(values).trigger('change.select2');
}
}
} else {
console.log("is NOT in array");
}
});
控制台值:
LOCATION (2) ["all", "trinidad and tobago"]
*********************
is in array
values-> (2) ["all", "trinidad and tobago"]
I-> 0
coming
values after-> ["trinidad and tobago"]
工作小提琴:
有人帮我解决这个问题。