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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With