最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to select all options in select2 JavaScript multiselect - Stack Overflow

programmeradmin4浏览0评论

The other day, I was trying to figure out how to select all items in select2 v3.5.1 JavaScript multiselect control. I tried a few things, but I was having a difficult time figuring out how to do it. I just wanted to select every option in the box, but apparently select2 does not have a built-in option to select all of the items for you.

The other day, I was trying to figure out how to select all items in select2 v3.5.1 JavaScript multiselect control. I tried a few things, but I was having a difficult time figuring out how to do it. I just wanted to select every option in the box, but apparently select2 does not have a built-in option to select all of the items for you.

Share Improve this question asked Aug 11, 2014 at 13:23 TargaryenTargaryen 1,0912 gold badges17 silver badges30 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

For select2 4.0.0

var selectedItems = [];
var allOptions = $("#IncludeFieldsMulti option");
allOptions.each(function() {
    selectedItems.push( $(this).val() );
});
$("#IncludeFieldsMulti").val(selectedItems).trigger("change"); 

Here's a slightly more efficient version of the OP's answer:

var selectedItems = [];
var allOptions = $("#IncludeFieldsMulti option");
allOptions.each(function() {
    selectedItems.push( $(this).val() );
});
$("#IncludeFieldsMulti").select2("val", selectedItems);

Or to make it more concise:

var selectedItems = $('#IncludeFieldsMulti option').map(function() { return this.value });
$("#IncludeFieldsMulti").select2("val", selectedItems);

Based on the discussion here: https://github.com/select2/select2/issues/195 it is possible to add a Select All button inside the dropdown list of options. Per that discussion, selecting too many at once can freeze the browser. Here I have added a functionality to disable the select all button if there are more that 25 options listed:

https://jsfiddle.net/hula_zell/50v60cm6/

To Select ALL

$("#IncludeFieldsMulti").select2("destroy");
$("#IncludeFieldsMulti").find('option').attr('selected',true);
$("#IncludeFieldsMulti").select2();

To Unselect ALL

$("#IncludeFieldsMulti").select2("destroy");
$("#IncludeFieldsMulti").find('option').attr('selected',false);
$("#IncludeFieldsMulti").select2();
发布评论

评论列表(0)

  1. 暂无评论