Targaryen
Targaryen

Reputation: 1091

How to select all options in select2 JavaScript multiselect

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.

Upvotes: 7

Views: 13526

Answers (4)

Usama Farooq
Usama Farooq

Reputation: 26

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();

Upvotes: 0

Hula_Zell
Hula_Zell

Reputation: 1250

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/

Upvotes: 3

R J
R J

Reputation: 91

For select2 4.0.0

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

Upvotes: 9

Matt Browne
Matt Browne

Reputation: 12419

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);

Upvotes: 6

Related Questions