How to select all options in select2 JavaScript multiselect

The other day I was trying to figure out how to select all the elements in the select2 v3.5.1 JavaScript multiselect element. I tried a few things, but it was hard for me to figure out how to do this. I just wanted to select each parameter in the field, but apparently select2 does not have a built-in option to select all the elements for you.

+5
source share
4 answers

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

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

Or make it more concise:

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

For select2 4.0.0

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

I figured out how to select all the items. It's a little weird how you need to do this with select2, but it works every time.

  var selectedItems = $('#IncludeFieldsMulti').select2('val'); var allOptions = $("#IncludeFieldsMulti option"); for (var i = 0; i < allOptions.length; i++) { selectedItems.push($(allOptions[i]).val()); } $("#IncludeFieldsMulti").select2("val", selectedItems); 
0
source

Based on the discussion here: https://github.com/select2/select2/issues/195, you can add the Select All button in the drop-down list of options. In this discussion, choosing too many can freeze the browser right away. Here I added functionality to disable the Select All button if there are more than 25 options:

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

0
source

Source: https://habr.com/ru/post/1200026/


All Articles