Targaryen Targaryen - 1 year ago 146
jQuery Question

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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download