Select all / Unselect all in Bootstrap Select plugin

后端 未结 8 2109
渐次进展
渐次进展 2021-01-02 03:34

    
    
    
    
    
    
    

Then the code to make it work the way I wanted was:

$('.selectpicker.select-all').on('change', function () {
    var selectPicker = $(this);
    var selectAllOption = selectPicker.find('option.select-all');
    var checkedAll = selectAllOption.prop('selected');
    var optionValues = selectPicker.find('option[value!="[all]"][data-divider!="true"]');

    if (checkedAll) {
        // Process 'all/none' checking
        var allChecked = selectAllOption.data("all") || false;

        if (!allChecked) {
            optionValues.prop('selected', true).parent().selectpicker('refresh');
            selectAllOption.data("all", true);
        }
        else {
            optionValues.prop('selected', false).parent().selectpicker('refresh');
            selectAllOption.data("all", false);
        }

        selectAllOption.prop('selected', false).parent().selectpicker('refresh');
    }
    else {
        // Clicked another item, determine if all selected
        var allSelected = optionValues.filter(":selected").length == optionValues.length;
        selectAllOption.data("all", allSelected);
    }
}).trigger('change');

Thanks @glyuck for the inspiration.

Fiddle: http://jsfiddle.net/3Lr4jsz0/

提交回复
热议问题