<!-- Style -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<!-- Script -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<script>
// In your Javascript (external.js resource or <script> tag)
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
</script>
$(document).ready(function() {
$("#menuOption1").select2({dropdownParent: "#menuOption1-container"});
$("#menuOption2").select2({dropdownParent: "#menuOption2-container"});
});
<span id="menuOption1-container">
<select id="menuOption1">
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
<option value="5"> Five </option>
</select>
</span>
<span id="menuOption2-container">
<select id="menuOption2">
<option value="a"> Vowel a </option>
<option value="e"> Vowel e </option>
<option value="i"> Vowel i </option>
<option value="o"> Vowel o </option>
<option value="o"> Vowel u </option>
</select>
</span>
$(".js-example-basic-multiple-limit").select2({
maximumSelectionLength: 3
});
$('.select2').select2({
placeholder: 'Press CTRL+A for selecr or unselect all options'
});
$('.select2[multiple]').siblings('.select2-container').append('<span class="select-all"></span>');
$(document).on('click', '.select-all', function (e) {
selectAllSelect2($(this).siblings('.selection').find('.select2-search__field'));
});
$(document).on("keyup", ".select2-search__field", function (e) {
var eventObj = window.event ? event : e;
if (eventObj.keyCode === 65 && eventObj.ctrlKey)
selectAllSelect2($(this));
});
function selectAllSelect2(that) {
var selectAll = true;
var existUnselected = false;
var item = $(that.parents("span[class*='select2-container']").siblings('select[multiple]'));
item.find("option").each(function (k, v) {
if (!$(v).prop('selected')) {
existUnselected = true;
return false;
}
});
selectAll = existUnselected ? selectAll : !selectAll;
item.find("option").prop('selected', selectAll);
item.trigger('change');
}
#menuOption1-container .select2-results__option--highlighted {
background-color: #50831F !important;
}
#menuOption2-container .select2-results__option--highlighted {
background-color: #28915F !important;
}
// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
$('.js-example-basic-single').select2();
});