Bootstrap multiselect Disable Checkbox
Disable Checkbox using bs Multiselect. disable Multiple check boxes.
by Amar Bhatia
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<select name="CelebInfluencerID" id="CelebInfluencerID" class="bs_multiselect" multiple data-max_limit="2" data-max_limit_msg="You have maxed out your limit of selecting 2 options." data-include-select-all-option="false">
<option value="1">Test</option>
<option value="2">Test</option>
<option value="3">Test</option>
</select>
JavaScript
bs_muliselect_init();
function bs_muliselect_init(selector = '') {
var selector = (selector != '') ? selector : '.bs_multiselect';
var selector_index = $(selector).index();
var selector_container_class = selector + '_container' + selector_index;
selector_container_class = selector_container_class.replace(/[.#]/g, '');
$(selector).multiselect({
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
includeSelectAllOption: true,
optionClass: function(element) {
return selector_container_class;
},
onChange: function(option, checked) {
var max_limit = $(selector).attr('data-max_limit');
var max_limit_msg = $(selector).attr('data-max_limit_msg');
var selectedOptions = $(selector + ' option:selected');
if (max_limit != undefined && max_limit != '' && !isNaN(max_limit)) {
if (selectedOptions.length == max_limit) {
alert(max_limit_msg);
// Disable all other checkboxes.
var nonSelectedOptions = $(selector + ' option').filter(function() {
return !$(this).is(':selected');
});
nonSelectedOptions.each(function() {
var input = $('.' + selector_container_class + ' input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
} else {
// Enable all checkboxes.
$(selector + ' option').each(function() {
var input = $('.' + selector_container_class + ' input[value="' + $(this).val() + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
});
}
}
}
});
}