Select2 demo

by harifrais

HTML

<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<link rel="stylesheet" href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css">
<select id="LOCATION" multiple="multiple" style="width: 300px">
   
</select>

JavaScript

data = [{id:"all",text:"all"},{id:"one",text:"one"},{id:"two",text:"two"},{id:"three",text:"three"},{id:"four",text:"four"}];


valuesToAccess = ["all"];



$('#LOCATION').select2({
    placeholder: 'Select a value',
    data: data,
    multiple:true,
    closeOnSelect:true
});

let $element = $('#LOCATION');
	var selectedValues = [];
	$.each( valuesToAccess, function( key, value ) {
		console.log(key,value);
		selectedValues.push($element.find("option:contains('"+value+"')").val());
	});
	$element.val(selectedValues).trigger('change.select2');
	
	



$('#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");
	} 

});