-1

I want to style checkboxes of bootstrap-multiselect plugin. Basically I want to add a class to label of selected checkbox. I can get the selected value this way but couldn't figure out how to target the checkbox.

<label class="checkbox">
   <input type="checkbox" value="red">Red
</label>

$('select').multiselect({
    onChange: function(element, checked) {
        var colors = $('select option:selected');
        $(colors).each(function(){
            $(this).parent().addClass('label-selected');
        });
    }
});

EDIT: The only way I found is to edit the plugin like that:

if (this.options.selectedClass) {
    if (checked) {
        $target.closest('li').addClass(this.options.selectedClass);
        $target.closest('li label').addClass('label-selected'); //ADDED THIS LINE
    }
    else {
        $target.closest('li').removeClass(this.options.selectedClass);
        $target.closest('li label').removeClass('label-selected'); //ADDED THIS LINE
    }
}
Dejavu
  • 703
  • 3
  • 9
  • 26

1 Answers1

0

I recommend doing this using the onChange option instead of manually editing the plugin (you may have troubles when updating to newer versions or integrating fixes). The following example can now also be found in the documentation:

<script type="text/javascript">
    $(document).ready(function() {
        $('#example-selected-parents').multiselect({
            buttonContainer: '<div id="example-selected-parents-container"></div>',
            onChange: function(options, selected) {
                // Get checkbox corresponding to option:
                var value = $(options).val();
                var $input = $('#example-selected-parents-container input[value="' + value + '"]');

                // Adapt label class:
                if (selected) {
                    $input.closest('label').addClass('active');
                }
                else {
                    $input.closest('label').removeClass('active');
                }
            }
        });
    });
</script>
<style type="text/css">
    #example-selected-parents-container label.active {
        font-weight: bold;
    }
</style>
<div class="btn-group">
    <select id="example-selected-parents" multiple="multiple">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
        <option value="5">Option 5</option>
        <option value="6">Option 6</option>
    </select>
</div>

You may have to adapt the onChange function in case you are also using optgroups (i.e. then multiple options are passed to onChange) or additional features. In these cases also have a look at the following options you may need to adapt:

  • onSelectAll
  • onDeselectAll
David Stutz
  • 2,578
  • 1
  • 17
  • 25