JQuery Select2 -如何选择所有选项

时间:2022-11-27 19:32:27

I'm using jQuery select2 multi select dropdown. I need to select all options in a dropdown from code. Basically there is a Select All checkbox on which this functionality has to be implemented, I want to select/deselect options from this checkbox.

我使用jQuery select2多选择下拉。我需要在代码的下拉菜单中选择所有选项。基本上,有一个选中的复选框,在这个复选框中,这个功能必须被实现,我想从这个复选框中选择/取消选择选项。

10 个解决方案

#1


8  

There is a description in thread on github. Quoting (https://github.com/ivaynberg/select2/issues/195#issuecomment-13489140 by MortadaAK) which allows you to select everything on ctrl+a

在github的thread上有一个描述。引用(https://github.com/ivaynberg/select2/issues/195# issues -13489140 by MortadaAK)可以让你在ctrl+a上选择一切

$(document).on("keypress",".select2-input",function(event){
    if (event.ctrlKey || event.metaKey) {
        var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
        var element =$("#"+id);
        if (event.which == 97){
            var selected = [];
            element.find("option").each(function(i,e){
                selected[selected.length]=$(e).attr("value");
            });
            element.select2("val", selected);
        } else if (event.which == 100){
            element.select2("val", "");
        }
    }
});

#2


43  

using Select 2 DEMO

使用选择2演示

$("#e1").select2();
$("#checkbox").click(function(){
    if($("#checkbox").is(':checked') ){
        $("#e1 > option").prop("selected","selected");// Select All Options
        $("#e1").trigger("change");// Trigger change to select 2
    }else{
        $("#e1 > option").removeAttr("selected");
        $("#e1").trigger("change");// Trigger change to select 2
     }
});

$("#button").click(function(){
       alert($("#e1").val());
});
<select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>
<input type="checkbox" id="checkbox" >Select All

<input type="button" id="button" value="check Selected">

You need code As shown in DEMO2 for Simple Select

要进行简单的选择,需要使用DEMO2中所示的代码

$("#checkbox").click(function(){
    if($("#checkbox").is(':checked') ){
        $("select > option").prop("selected","selected");
    }else{
        $("select > option").removeAttr("selected");
     }
});

$("#button").click(function(){
       alert($("select").val());
});

<select multiple size=2>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select> <input type="checkbox" id="checkbox" >Select All

<input type="button" id="button" value="check Selected">

#3


6  

you could do it for one string

你可以用一根弦来做

$('select.your-select option').attr('selected', true).parent().trigger('change')

#4


4  

$(document).ready(function() {
    $("#checkbox").click(function(){
      if($("#checkbox").is(':checked') ){ //select all
        $("#e1").find('option').prop("selected",true);
        $("#e1").trigger('change');
      } else { //deselect all
        $("#e1").find('option').prop("selected",false);
        $("#e1").trigger('change');
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>     //AJAX created
        <option value="Am">Amalapuram</option>  //AJAX created
        <option value="An">Anakapalli</option>  //AJAX created
        <option value="Ak">Akkayapalem</option> //AJAX created
        <option value="WY">Wyoming</option>     //AJAX created
    </select>
    <input type="checkbox" id="checkbox" >Select All

If options are created after AJAX request then these options don't work. So we map them with find and select/unselect them , after that trigger change.

如果在AJAX请求之后创建了选项,那么这些选项将不起作用。我们用find和select/unselect来映射它们,在触发器更改之后。

HTML

HTML

 <select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>     //AJAX created
        <option value="Am">Amalapuram</option>  //AJAX created
        <option value="An">Anakapalli</option>  //AJAX created
        <option value="Ak">Akkayapalem</option> //AJAX created
        <option value="WY">Wyoming</option>     //AJAX created
    </select>
    <input type="checkbox" id="checkbox" >Select All

JS

JS

$(document).ready(function() {
    $("#checkbox").click(function(){
      if($("#checkbox").is(':checked') ){ //select all
        $("#e1").find('option').prop("selected",true);
        $("#e1").trigger('change');
      } else { //deselect all
        $("#e1").find('option').prop("selected",false);
        $("#e1").trigger('change');
      }
  });
});

just use find.

只使用。

#5


2  

$('.select2').select2({
  placeholder: 'Press CTRL+A for selecr or unselect all options'
});

$('.select2[multiple]').siblings('.select2-container').append('<span class="select-all"></span>');

$(document).on('click', '.select-all', function (e) {
  selectAllSelect2($(this).siblings('.selection').find('.select2-search__field'));
});

$(document).on("keyup", ".select2-search__field", function (e) {
  var eventObj = window.event ? event : e;
  if (eventObj.keyCode === 65 && eventObj.ctrlKey)
     selectAllSelect2($(this));
});
        
        
function selectAllSelect2(that) {

  var selectAll = true;
  var existUnselected = false;
  var id = that.parents("span[class*='select2-container']").siblings('select[multiple]').attr('id');
  var item = $("#" + id);

  item.find("option").each(function (k, v) {
      if (!$(v).prop('selected')) {
          existUnselected = true;
          return false;
      }
  });

  selectAll = existUnselected ? selectAll : !selectAll;

  item.find("option").prop('selected', selectAll).trigger('change');
}
.select2-container {
  width: 90% !important;
}

.select2-container .select-all {
		position: absolute;
		top: 6px;
		right: 4px;
		width: 20px;
		height: 20px;
		margin: auto;
		display: block;
		background: url('data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjUxMnB4IiBoZWlnaHQ9IjUxMnB4IiB2aWV3Qm94PSIwIDAgNDc0LjggNDc0LjgwMSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3Jv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KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K') no-repeat center;
		background-size: contain;
		cursor: pointer;
		z-index: 999999;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<select class="select2" multiple id="my-select">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>

#6


2  

Answer from here works pretty good.

这里的答案很不错。

// Select all
$('#select-id').select2('destroy').find('option').prop('selected', 'selected').end().select2();

// Unselect all
$('#select-id').select2('destroy').find('option').prop('selected', false).end().select2();

#7


1  

@Garath: I have tweaked your posted code in order to make it work with results that are loaded via ajax. Thank you for bringing this up here.

@Garath:我已经修改了您发布的代码,以使其与通过ajax加载的结果一起工作。谢谢你把这个带到这里来。

    $(document).on("keypress",".select2-input",function(event){
    if (event.ctrlKey || event.metaKey) {
        var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
        var element =$("#"+id);
        if (event.which == 97){
            var selected = [];
            $('.select2-drop-active').find("ul.select2-results li").each(function(i,e){
                selected.push($(e).data("select2-data"));
            });
            element.select2("data", selected);
        } else if (event.which == 100){
            element.select2("data", []);
        }
    }
});

#8


1  

Info: The values for gSiteIDs are the values used when originally dynamically creating the select options. #selAllSites is the id of a checkbox and #siteID is the id of the select list you want to manipulate.

Info: gsiteid的值是最初动态创建select选项时使用的值。#selAllSites是复选框的id, #siteID是您要操作的选择列表的id。

var gSiteIDs = "8475, 9082, 2387, 1234";

function selectAllSites() 
{
    if($("#selAllSites").is(":Checked")) {
        $("#siteID").select2("val", [gSiteIDs]);                                
    } else {
        $("#siteID").select2("val", []);                                
    }
}           

#9


0  

This works great with AJAX, prevents from opening Bookmarks window in FF (Ctrl-D), and works fine when closeOnSelect is set to off.

这在AJAX中非常有用,可以防止在FF (Ctrl-D)中打开书签窗口,在将closeOnSelect设置为off时也很好用。

$(document).on("keypress",".select2-input",function(event){
    if (event.ctrlKey || event.metaKey) {
        var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
        var element =$("#"+id);

        if (event.which == 97){
            var selected = [];
            $('.select2-drop-active').find("ul.select2-results li").each(function(i,e){
                selected.push($(e).data("select2-data"));
            });
            element.select2("data", selected);
            element.select2("focus");
            event.preventDefault();
        } else if (event.which == 100){
            element.select2("data", []);
            event.preventDefault();
        }
    }
});

#10


0  

$.fn.select2.amd.require([
    'select2/utils',
    'select2/dropdown',
    'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
    function SelectAll() { }

    SelectAll.prototype.render = function (decorated) {
        var $rendered = decorated.call(this);
        var self = this;

        var $selectAll = $(
            '<button type="button" style="width: 100%; height: 3rem; text-align: left; color: blue; background: none; border: none; box-shadow: none">Select All</button>'
        );

        $rendered.find('.select2-dropdown').prepend($selectAll);

        $selectAll.on('click', function (e) {
            var $results = $rendered.find('.select2-results__option[aria-selected=false]');

            // Get all results that aren't selected
            $results.each(function () {
                var $result = $(this);

                // Get the data object for it
                var data = $result.data('data');

                // Trigger the select event
                self.trigger('select', {
                    data: data
                });
            });

            self.trigger('close');
        });

        return $rendered;
    };

    $("#select-id").select2({
        placeholder: "Select weekdays...",
        allowClear: true,
        dropdownAdapter: Utils.Decorate(
            Utils.Decorate(
                Dropdown,
                AttachBody
            ),
            SelectAll
        )
    });
});

Source code: http://jsbin.com/seqonozasu/1/edit?html,js,output

源代码:http://jsbin.com/seqonozasu/1/edit?html、js、输出

#1


8  

There is a description in thread on github. Quoting (https://github.com/ivaynberg/select2/issues/195#issuecomment-13489140 by MortadaAK) which allows you to select everything on ctrl+a

在github的thread上有一个描述。引用(https://github.com/ivaynberg/select2/issues/195# issues -13489140 by MortadaAK)可以让你在ctrl+a上选择一切

$(document).on("keypress",".select2-input",function(event){
    if (event.ctrlKey || event.metaKey) {
        var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
        var element =$("#"+id);
        if (event.which == 97){
            var selected = [];
            element.find("option").each(function(i,e){
                selected[selected.length]=$(e).attr("value");
            });
            element.select2("val", selected);
        } else if (event.which == 100){
            element.select2("val", "");
        }
    }
});

#2


43  

using Select 2 DEMO

使用选择2演示

$("#e1").select2();
$("#checkbox").click(function(){
    if($("#checkbox").is(':checked') ){
        $("#e1 > option").prop("selected","selected");// Select All Options
        $("#e1").trigger("change");// Trigger change to select 2
    }else{
        $("#e1 > option").removeAttr("selected");
        $("#e1").trigger("change");// Trigger change to select 2
     }
});

$("#button").click(function(){
       alert($("#e1").val());
});
<select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>
<input type="checkbox" id="checkbox" >Select All

<input type="button" id="button" value="check Selected">

You need code As shown in DEMO2 for Simple Select

要进行简单的选择,需要使用DEMO2中所示的代码

$("#checkbox").click(function(){
    if($("#checkbox").is(':checked') ){
        $("select > option").prop("selected","selected");
    }else{
        $("select > option").removeAttr("selected");
     }
});

$("#button").click(function(){
       alert($("select").val());
});

<select multiple size=2>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select> <input type="checkbox" id="checkbox" >Select All

<input type="button" id="button" value="check Selected">

#3


6  

you could do it for one string

你可以用一根弦来做

$('select.your-select option').attr('selected', true).parent().trigger('change')

#4


4  

$(document).ready(function() {
    $("#checkbox").click(function(){
      if($("#checkbox").is(':checked') ){ //select all
        $("#e1").find('option').prop("selected",true);
        $("#e1").trigger('change');
      } else { //deselect all
        $("#e1").find('option').prop("selected",false);
        $("#e1").trigger('change');
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>     //AJAX created
        <option value="Am">Amalapuram</option>  //AJAX created
        <option value="An">Anakapalli</option>  //AJAX created
        <option value="Ak">Akkayapalem</option> //AJAX created
        <option value="WY">Wyoming</option>     //AJAX created
    </select>
    <input type="checkbox" id="checkbox" >Select All

If options are created after AJAX request then these options don't work. So we map them with find and select/unselect them , after that trigger change.

如果在AJAX请求之后创建了选项,那么这些选项将不起作用。我们用find和select/unselect来映射它们,在触发器更改之后。

HTML

HTML

 <select multiple id="e1" style="width:300px">
        <option value="AL">Alabama</option>     //AJAX created
        <option value="Am">Amalapuram</option>  //AJAX created
        <option value="An">Anakapalli</option>  //AJAX created
        <option value="Ak">Akkayapalem</option> //AJAX created
        <option value="WY">Wyoming</option>     //AJAX created
    </select>
    <input type="checkbox" id="checkbox" >Select All

JS

JS

$(document).ready(function() {
    $("#checkbox").click(function(){
      if($("#checkbox").is(':checked') ){ //select all
        $("#e1").find('option').prop("selected",true);
        $("#e1").trigger('change');
      } else { //deselect all
        $("#e1").find('option').prop("selected",false);
        $("#e1").trigger('change');
      }
  });
});

just use find.

只使用。

#5


2  

$('.select2').select2({
  placeholder: 'Press CTRL+A for selecr or unselect all options'
});

$('.select2[multiple]').siblings('.select2-container').append('<span class="select-all"></span>');

$(document).on('click', '.select-all', function (e) {
  selectAllSelect2($(this).siblings('.selection').find('.select2-search__field'));
});

$(document).on("keyup", ".select2-search__field", function (e) {
  var eventObj = window.event ? event : e;
  if (eventObj.keyCode === 65 && eventObj.ctrlKey)
     selectAllSelect2($(this));
});
        
        
function selectAllSelect2(that) {

  var selectAll = true;
  var existUnselected = false;
  var id = that.parents("span[class*='select2-container']").siblings('select[multiple]').attr('id');
  var item = $("#" + id);

  item.find("option").each(function (k, v) {
      if (!$(v).prop('selected')) {
          existUnselected = true;
          return false;
      }
  });

  selectAll = existUnselected ? selectAll : !selectAll;

  item.find("option").prop('selected', selectAll).trigger('change');
}
.select2-container {
  width: 90% !important;
}

.select2-container .select-all {
		position: absolute;
		top: 6px;
		right: 4px;
		width: 20px;
		height: 20px;
		margin: auto;
		display: block;
		background: url('data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjUxMnB4IiBoZWlnaHQ9IjUxMnB4IiB2aWV3Qm94PSIwIDAgNDc0LjggNDc0LjgwMSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDc0LjggNDc0LjgwMTsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8Zz4KCTxnPgoJCTxwYXRoIGQ9Ik0zOTYuMjgzLDI1Ny4wOTdjLTEuMTQtMC41NzUtMi4yODItMC44NjItMy40MzMtMC44NjJjLTIuNDc4LDAtNC42NjEsMC45NTEtNi41NjMsMi44NTdsLTE4LjI3NCwxOC4yNzEgICAgYy0xLjcwOCwxLjcxNS0yLjU2Ni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
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<select class="select2" multiple id="my-select">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>

#6


2  

Answer from here works pretty good.

这里的答案很不错。

// Select all
$('#select-id').select2('destroy').find('option').prop('selected', 'selected').end().select2();

// Unselect all
$('#select-id').select2('destroy').find('option').prop('selected', false).end().select2();

#7


1  

@Garath: I have tweaked your posted code in order to make it work with results that are loaded via ajax. Thank you for bringing this up here.

@Garath:我已经修改了您发布的代码,以使其与通过ajax加载的结果一起工作。谢谢你把这个带到这里来。

    $(document).on("keypress",".select2-input",function(event){
    if (event.ctrlKey || event.metaKey) {
        var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
        var element =$("#"+id);
        if (event.which == 97){
            var selected = [];
            $('.select2-drop-active').find("ul.select2-results li").each(function(i,e){
                selected.push($(e).data("select2-data"));
            });
            element.select2("data", selected);
        } else if (event.which == 100){
            element.select2("data", []);
        }
    }
});

#8


1  

Info: The values for gSiteIDs are the values used when originally dynamically creating the select options. #selAllSites is the id of a checkbox and #siteID is the id of the select list you want to manipulate.

Info: gsiteid的值是最初动态创建select选项时使用的值。#selAllSites是复选框的id, #siteID是您要操作的选择列表的id。

var gSiteIDs = "8475, 9082, 2387, 1234";

function selectAllSites() 
{
    if($("#selAllSites").is(":Checked")) {
        $("#siteID").select2("val", [gSiteIDs]);                                
    } else {
        $("#siteID").select2("val", []);                                
    }
}           

#9


0  

This works great with AJAX, prevents from opening Bookmarks window in FF (Ctrl-D), and works fine when closeOnSelect is set to off.

这在AJAX中非常有用,可以防止在FF (Ctrl-D)中打开书签窗口,在将closeOnSelect设置为off时也很好用。

$(document).on("keypress",".select2-input",function(event){
    if (event.ctrlKey || event.metaKey) {
        var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
        var element =$("#"+id);

        if (event.which == 97){
            var selected = [];
            $('.select2-drop-active').find("ul.select2-results li").each(function(i,e){
                selected.push($(e).data("select2-data"));
            });
            element.select2("data", selected);
            element.select2("focus");
            event.preventDefault();
        } else if (event.which == 100){
            element.select2("data", []);
            event.preventDefault();
        }
    }
});

#10


0  

$.fn.select2.amd.require([
    'select2/utils',
    'select2/dropdown',
    'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
    function SelectAll() { }

    SelectAll.prototype.render = function (decorated) {
        var $rendered = decorated.call(this);
        var self = this;

        var $selectAll = $(
            '<button type="button" style="width: 100%; height: 3rem; text-align: left; color: blue; background: none; border: none; box-shadow: none">Select All</button>'
        );

        $rendered.find('.select2-dropdown').prepend($selectAll);

        $selectAll.on('click', function (e) {
            var $results = $rendered.find('.select2-results__option[aria-selected=false]');

            // Get all results that aren't selected
            $results.each(function () {
                var $result = $(this);

                // Get the data object for it
                var data = $result.data('data');

                // Trigger the select event
                self.trigger('select', {
                    data: data
                });
            });

            self.trigger('close');
        });

        return $rendered;
    };

    $("#select-id").select2({
        placeholder: "Select weekdays...",
        allowClear: true,
        dropdownAdapter: Utils.Decorate(
            Utils.Decorate(
                Dropdown,
                AttachBody
            ),
            SelectAll
        )
    });
});

Source code: http://jsbin.com/seqonozasu/1/edit?html,js,output

源代码:http://jsbin.com/seqonozasu/1/edit?html、js、输出