Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
Targaryen Avatar asked Aug 11 '14 13:08

Targaryen


3 Answers

For select2 4.0.0

var selectedItems = [];
var allOptions = $("#IncludeFieldsMulti option");
allOptions.each(function() {
    selectedItems.push( $(this).val() );
});
$("#IncludeFieldsMulti").val(selectedItems).trigger("change"); 
like image 131
R J Avatar answered Nov 01 '22 14:11

R J


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);
like image 24
Matt Browne Avatar answered Nov 01 '22 13:11

Matt Browne


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/

like image 21
Hula_Zell Avatar answered Nov 01 '22 14:11

Hula_Zell