Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 onselect an option will select all other option

I have a select 2 provided in this JSFIDDLE. How can I onselect an option call All it will select all of the option inside that select field except for itself, meaning the All option is more like a Select All button. and deselecting the All. will deselect all option. I provide the same code from the jsfiddle below :

HTML :

<select class="parent_filter_select2 pull-right" id="parent_filter_select2" multiple="multiple" name="select_project" style="width: 300px;">
<option value="all">All</option>
        <option value="Option A">Option A</option>
        <option value="Option B">Option B</option>
        <option value="Option C">Option C</option>
        <option value="Option D">Option D</option>
</select>

Javascript :

$('#parent_filter_select2').select2({
    placeholder: 'Select'
});

Any help is much appreciated, thanks.

UPDATE : I found something similar like I've wanted but its using checkbox instead so Im figuring how to implement it on the All option instead of a checkbox, and also with this its selecting the All option too, code below :

$("#checkbox").click(function(){
      if($("#checkbox").is(':checked') ){ //select all
        $("#parent_filter_select2").find('option').prop("selected",true);
        $("#parent_filter_select2").trigger('change');
      } else { //deselect all
        $("#parent_filter_select2").find('option').prop("selected",false);
        $("#parent_filter_select2").trigger('change');
      }
  });
like image 515
M.Izzat Avatar asked Dec 27 '17 03:12

M.Izzat


3 Answers

There is an open issue on Select2 github repo, see: select all / select none header

As suggested by 'bkdotcom' user (see comment) you can define a selectAllAdapter and use it with Select2 (version 4).

Check your fiddle updated: https://jsfiddle.net/beaver71/tjvjytp3/

or this snippet:

/*
      Define the adapter so that it's reusable
*/         
$.fn.select2.amd.define('select2/selectAllAdapter', [
    'select2/utils',
    'select2/dropdown',
    'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {

    function SelectAll() { }
    SelectAll.prototype.render = function (decorated) {
        var self = this,
            $rendered = decorated.call(this),
            $selectAll = $(
                '<button class="btn btn-xs btn-default" type="button" style="margin-left:6px;"><i class="fa fa-check-square-o"></i> Select All</button>'
            ),
            $unselectAll = $(
                '<button class="btn btn-xs btn-default" type="button" style="margin-left:6px;"><i class="fa fa-square-o"></i> Unselect All</button>'
            ),
            $btnContainer = $('<div style="margin-top:3px;">').append($selectAll).append($unselectAll);
        if (!this.$element.prop("multiple")) {
            // this isn't a multi-select -> don't add the buttons!
            return $rendered;
        }
        $rendered.find('.select2-dropdown').prepend($btnContainer);
        $selectAll.on('click', function (e) {
            var $results = $rendered.find('.select2-results__option[aria-selected=false]');
            $results.each(function () {
                self.trigger('select', {
                    data: $(this).data('data')
                });
            });
            self.trigger('close');
        });
        $unselectAll.on('click', function (e) {
            var $results = $rendered.find('.select2-results__option[aria-selected=true]');
            $results.each(function () {
                self.trigger('unselect', {
                    data: $(this).data('data')
                });
            });
            self.trigger('close');
        });
        return $rendered;
    };

    return Utils.Decorate(
        Utils.Decorate(
            Dropdown,
            AttachBody
        ),
        SelectAll
    );

});

$('#parent_filter_select2').select2({
    placeholder: 'Select',
    dropdownAdapter: $.fn.select2.amd.require('select2/selectAllAdapter')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>

<select class="parent_filter_select2 pull-right" id="parent_filter_select2" multiple="multiple" name="select_project" style="width: 300px;">
        <option value="Option A">Option A</option>
        <option value="Option B">Option B</option>
        <option value="Option C">Option C</option>
        <option value="Option D">Option D</option>
</select>
like image 131
beaver Avatar answered Oct 11 '22 06:10

beaver


Use the following script

$("#parent_filter_select2 option").click(function () {
    var val = $(this).attr("value");
    if(val == 'all'){
        $('#parent_filter_select2 option').prop('selected', true);
        $('#parent_filter_select2 option[value="all"]').prop('selected', false);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="parent_filter_select2 pull-right" id="parent_filter_select2" multiple="multiple" name="select_project" style="width: 300px;">
<option value="all">All</option>
        <option value="Option A">Option A</option>
        <option value="Option B">Option B</option>
        <option value="Option C">Option C</option>
        <option value="Option D">Option D</option>
</select>
like image 27
jun drie Avatar answered Oct 11 '22 06:10

jun drie


you can select option manually by using

$('#parent_filter_select2').select2('val', values);

on select option All from your dropdown.

where you can take values as javascript array.

 var values = new Array();
$('#parent_filter_select2').find('option').each(function () {
    var opt= $(this);
    var opvalue= opt.attr('value');
    if(opvalue != "all")
        values.push(opvalue);        
});

sample code is here.

  $('body').on('change', '#parent_filter_select2', function () {
 var val = $(this).val();
    //alert(val);
    if(val.indexOf('all') != -1){
            $('#parent_filter_select2').select2('val', values);
         }
        else{
            $('#parent_filter_select2').select2('val', val);
        }
});

you can check jsfiddle demo here

see if it helps..

like image 35
Saurabh Solanki Avatar answered Oct 11 '22 05:10

Saurabh Solanki