Select all / Unselect all in Bootstrap Select plugin
Asked Answered
D

8

18
<select id="divRatings" class="selectpicker" multiple title='Choose one of the following...' data-size="5" data-selected-text-format="count>2">
    <option value="All" selected="selected">All Ratings</option>
    <option value="EC">EC (Early Childhood)</option>
    <option value="E">E (Everyone)</option>
    <option value="E10+">E10+ (Everyone 10+)</option>
    <option value="T">T (Teen)</option>
    <option value="M">M (Mature)</option>
    <option value="AO">AO (Adults Only)</option>
</select>

In html above there are option with value All. I want to select all items if that option is selected and unselect all if i unselect this option.

I think it will be simple to do, but i can't get why nothing happens on $('#divRatings').change(function(){//some logic});

My function to select/ unselect items:

function toggleSelectAll(control) {
    if (control.val().indexOf("All,") > -1) {
        control.selectpicker('selectAll');
    } else {
        control.selectpicker('deselectAll');
    }
}

JSFiddle example

Discography answered 23/1, 2015 at 13:48 Comment(0)
M
8

Problem with your javascript is that anytime user clicks any option you check, if "All ratings" option is still checked - you check all other options too (even if you just unchecked any option). And if "All ratings" is unchecked, you uncheck all other options. So, in fact only "All ratings" option is clickable. If you click any other option, it's immediatelly checked/unchecked in your onchange handler.

Try this code:

function toggleSelectAll(control) {
    var allOptionIsSelected = (control.val() || []).indexOf("All") > -1;
    function valuesOf(elements) {
        return $.map(elements, function(element) {
            return element.value;
        });
    }

    if (control.data('allOptionIsSelected') != allOptionIsSelected) {
        // User clicked 'All' option
        if (allOptionIsSelected) {
            // Can't use .selectpicker('selectAll') because multiple "change" events will be triggered
            control.selectpicker('val', valuesOf(control.find('option')));
        } else {
            control.selectpicker('val', []);
        }
    } else {
        // User clicked other option
        if (allOptionIsSelected && control.val().length != control.find('option').length) {
            // All options were selected, user deselected one option
            // => unselect 'All' option
            control.selectpicker('val', valuesOf(control.find('option:selected[value!=All]')));
            allOptionIsSelected = false;
        } else if (!allOptionIsSelected && control.val().length == control.find('option').length - 1) {
            // Not all options were selected, user selected all options except 'All' option
            // => select 'All' option too
            control.selectpicker('val', valuesOf(control.find('option')));
            allOptionIsSelected = true;
        }
    }
    control.data('allOptionIsSelected', allOptionIsSelected);
}

$('#divRatings').selectpicker().change(function(){toggleSelectAll($(this));}).trigger('change');

http://jsfiddle.net/bu5vjdk6/4/


Updated code
http://jsfiddle.net/surajkm33/tsomyckj/

Meghan answered 23/1, 2015 at 15:9 Comment(6)
Thanks a lot, you did a big job as for me) Can i remove .selectpicker() from last line? I try it in jsFiddle, seems to work. Because in my project .selectpicker() in undefined even if library is loadedDiscography
Yes, remove it. I added it to ensure '.selectpicker()' is applied to select before I call .trigger('change') on it (which is called to actualize select's initial state).Meghan
Can you said what can cause this problem : TypeError: control.selectpicker is not a function (control.selectpicker('val', []);) Because i can't get what is it. I check if i include all libraries like jquery bootstrap and bootstrap-selectDiscography
Try to wrap your code with $(function() { // code here });. Or remove .trigger from last line of my script.Meghan
@glyuck, when i remove selectpicker() and trigger() then i can't access toggle functionDiscography
Wish I could upvote 10 times more. Your answer is well explained, elegant and does the trick. Thanks a lot.Relevant
L
20

Use data-actions-box="true" attribute to get select all and deselect all option. Try this code

<select id="divRatings" class="selectpicker" multiple title='Choose one of the following...' data-size="5" data-selected-text-format="count>2" data-actions-box="true">
            <option value="All" selected="selected">All Ratings</option>
            <option value="EC">EC (Early Childhood)</option>
            <option value="E">E (Everyone)</option>
            <option value="E10+">E10+ (Everyone 10+)</option>
            <option value="T">T (Teen)</option>
            <option value="M">M (Mature)</option>
            <option value="AO">AO (Adults Only)</option>
        </select>

Please visit [https://silviomoreto.github.io/bootstrap-select/options/][1]

[1]: https://silviomoreto.github.io/bootstrap-select/options/ To Know more

Hope this help...

Latex answered 27/3, 2017 at 8:21 Comment(0)
E
14

It has been answered, but I found a better way of doing (link to documentation).

Just add data-actions-box="true" as attributes of the select tag.

Eg.

<label>Select/deselect all</label>
<select class="selectpicker form-control" data-style="btn-outline-warning" multiple data-actions-box="true">
    <optgroup label="Condiments">
        <option>Mustard</option>
        <option>Ketchup</option>
        <option>Relish</option>
    </optgroup>
    <optgroup label="Breads">
        <option>Plain</option>
        <option>Steamed</option>
        <option>Toasted</option>
    </optgroup>
</select>

Expressionism answered 29/5, 2020 at 22:51 Comment(1)
This should be the accepted answer, just missing a link to the docs.Insolvency
B
13

Try this select All

$('#idSelect option').attr("selected","selected");
$('#idSelect').selectpicker('refresh');

Unselect All

$('#idSelect option').attr("selected",false);
$('#idSelect').selectpicker('refresh');

for my, this worked.

Blintz answered 26/11, 2015 at 15:26 Comment(0)
M
8

Problem with your javascript is that anytime user clicks any option you check, if "All ratings" option is still checked - you check all other options too (even if you just unchecked any option). And if "All ratings" is unchecked, you uncheck all other options. So, in fact only "All ratings" option is clickable. If you click any other option, it's immediatelly checked/unchecked in your onchange handler.

Try this code:

function toggleSelectAll(control) {
    var allOptionIsSelected = (control.val() || []).indexOf("All") > -1;
    function valuesOf(elements) {
        return $.map(elements, function(element) {
            return element.value;
        });
    }

    if (control.data('allOptionIsSelected') != allOptionIsSelected) {
        // User clicked 'All' option
        if (allOptionIsSelected) {
            // Can't use .selectpicker('selectAll') because multiple "change" events will be triggered
            control.selectpicker('val', valuesOf(control.find('option')));
        } else {
            control.selectpicker('val', []);
        }
    } else {
        // User clicked other option
        if (allOptionIsSelected && control.val().length != control.find('option').length) {
            // All options were selected, user deselected one option
            // => unselect 'All' option
            control.selectpicker('val', valuesOf(control.find('option:selected[value!=All]')));
            allOptionIsSelected = false;
        } else if (!allOptionIsSelected && control.val().length == control.find('option').length - 1) {
            // Not all options were selected, user selected all options except 'All' option
            // => select 'All' option too
            control.selectpicker('val', valuesOf(control.find('option')));
            allOptionIsSelected = true;
        }
    }
    control.data('allOptionIsSelected', allOptionIsSelected);
}

$('#divRatings').selectpicker().change(function(){toggleSelectAll($(this));}).trigger('change');

http://jsfiddle.net/bu5vjdk6/4/


Updated code
http://jsfiddle.net/surajkm33/tsomyckj/

Meghan answered 23/1, 2015 at 15:9 Comment(6)
Thanks a lot, you did a big job as for me) Can i remove .selectpicker() from last line? I try it in jsFiddle, seems to work. Because in my project .selectpicker() in undefined even if library is loadedDiscography
Yes, remove it. I added it to ensure '.selectpicker()' is applied to select before I call .trigger('change') on it (which is called to actualize select's initial state).Meghan
Can you said what can cause this problem : TypeError: control.selectpicker is not a function (control.selectpicker('val', []);) Because i can't get what is it. I check if i include all libraries like jquery bootstrap and bootstrap-selectDiscography
Try to wrap your code with $(function() { // code here });. Or remove .trigger from last line of my script.Meghan
@glyuck, when i remove selectpicker() and trigger() then i can't access toggle functionDiscography
Wish I could upvote 10 times more. Your answer is well explained, elegant and does the trick. Thanks a lot.Relevant
S
0
$('.selectpicker option[value=All]').click(function(){
    $('.selectpicker option').each(function(){
        this.selected = $('.selectpicker option[value=All]').attr('selected');
    });
});
Strychnic answered 23/1, 2015 at 13:57 Comment(1)
logical answer, but still didn't work jsfiddle.net/bu5vjdk6/1 Don't know whyDiscography
S
0

You can use my functions :

first change your code

<option value="All" selected="selected">All Ratings</option>

to

<option value="All" id="target" selected="selected">All Ratings</option>

and second add between your <script> tags

$( "#target" ).toggle(function() {
  selectAll($( "#divRatings" ))
}, function() {
  selectClear($( "#divRatings" ))
});

function selectAll(element){//Select All Function
    element.prop('selected', true);
    element.selectpicker('refresh');
}
function selectClear(element){//Clear All Function
    element.prop('selected', false);
    element.selectpicker('refresh');
}
Splashdown answered 29/4, 2017 at 15:9 Comment(0)
M
0

I started with @glyuck answer but changed it a little bit. I didn't want the 'All' item to be selected and then have the bootstrap-select show 'N items selected' in which one of them was the 'All' item. So basically, for me, that item will 'never select', it is more or less just a 'button' to toggle the states.

My markup would look like this:

<select size="4" multiple="multiple" class="form-control selectpicker show-tick select-all" data-selected-text-format="count > 2">
    <option value="[all]" class="select-all">All Items</option>
    <option value="" data-divider="true"></option>
    <option value="0">Members Selected</option>
    <option value="1">Separated Members Selected</option>
    <option value="2">Request Approval</option>
    <option value="3">Approved</option>
    <option value="4">Rejected</option>
</select>

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/

Marolda answered 1/6, 2019 at 21:57 Comment(0)
H
-1

I came accross this question while seeking for a quick solution to toggle on/off all option in a selectpicker <select> and I ended up drafting my own, one-liner style, that works for both on and off states:

So for a given select#my-select:

HTML

<div>
    <input type="checkbox" id="select_all" data-id-select="my-select">
    <label for="select_all">Toggle all</label>
</div>

JS/jQuery

$('#select_all').on('click', function() {
    $('#' + $(this).data('id-select')).find('option').prop('selected', $(this).is(':checked')).parent('select').selectpicker('refresh');
});
Hamlett answered 7/2, 2019 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.