Select2 Multi Select Select all when select all option

Here is a example of select2 with added styling and if user choose option all then each and every option should be selected.

Select2 Multi-Selection select all when select all

Select2 Multi-Selection select all when select all

HTML for select2




<div id="clr_cont" class="contains">
	<small>Select your favorite colors</small>
	<select class="fav_clr form-control" name="states[]" multiple="multiple">
<option value="all">all</option>
<option>orange</option>
<option>yellow</option>
<option>green</option>
<option>blue</option>
<option>pink</option>
<option>purple</option>
	</select>
</div>



JavaScript For Select2

$(document).ready(function() {
    $('.fav_clr').select2({
		placeholder: 'colors',
		width: '100%',
		border: '1px solid #e4e5e7',
    });
});

$('.fav_clr').on("select2:select", function (e) { 
           var data = e.params.data.text;
           if(data=='all'){
            $(".fav_clr > option").prop("selected","selected");
            $(".fav_clr").trigger("change");
           }
      });


CSS For Select2 styling

.select2-container--default.select2-container--focus .select2-selection--multiple {
	border: 1px solid #333 !important;
} 
.select2 .select2-container .select2-container--default .select2-container--focus {
	border: 1px solid #333 !important;
}
.select2-container--default .select2-selection--multiple {
	border: 1px solid #333 !important;
}
.select2-search__field {
	background-color: white !important;
}
.select2-dropdown .select2-dropdown--below {
	border: 1px solid #333 !important;
}
.select2-results {
	background-color: #444;
	height: 100px;
	color: #222;
}
.select2-results__options {
	height: 100px;
}
body {
	background-color: #222;
	padding: 20px;
}
small {
	color: white;
}
.contains {
	background-color: #333;
	width: 500px;
	display: inline-block;
	padding: 20px;
	border-radius: 5px;
}

Check demo here : Select2 Multi Select all option example



The following two tabs change content below.
Umar Farooque Khan is Software developer and professional blogger serving Worldwide on freelancer and ODesk platform to show the capability of his skills. He is the founder of pTutorial.com. The main purpose of this site is sharing and exchanging of Knowledge related to the recent technologies.