How to select all options in select2 JavaScript multiselect - javascript

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/

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

Related

Adding new value and selecting clears previous selections - Select2 multiple

After some fun and games I finally worked out how to dynamically (on button press) add and select a new value to a multiple Select2 select control populated from an MVC model on page load...
<select id="topicMaintMultiSelect" multiple="multiple" name="SelectedMaintTopic" tabindex="18" required="required">
#foreach (var topic in Model.SystemTopics.AvailableTopics)
{
<option value=#topic.Value selected=#topic.Selected>#topic.Text</option>
}
</select>
...and...
function addTopic() {
var newTopic = $("#NewTopic").val();
var select = document.getElementById("topicMaintMultiSelect");
var opt = new Option(newTopic, newTopic);
select.options[select.options.length] = opt;
opt.setAttribute("selected", "selected");
$("#topicMaintMultiSelect").val(newTopic).trigger("change");
$("#NewTopic").val("");
}
...but I cannot work out how to stop it from clearing the previously selected values.
I've tried a variety of suggested solutions, most of which are based on pushing a value into the select2 data but none of these seem to work, not sure why though.
Thoughts/suggestions, please.
Remove the call to .val(newTopic). That is what is clearing the previously selected values.
Adding an option that is marked as selected and triggering a change event is enough to change the value.
var newTopic = $('#NewTopic').val();
var $option = $('<option></option>').val(newTopic).text(newTopic).prop('selected', true);
$('#topicMaintMultiSelect').append($option).change();
jsfiddle for Select2 v4
jsfiddle for Select2 v3.5.3

Select2 multiple-select - programmatically deselect/unselect item

I have a select2 list and a set of external buttons. I wanted to click the external buttons and unselect corresponding items in the select2 list. I know I can do item selection from external value using the command
$("#external_btn").click(function() {
$("#select2").val("CA").trigger("change");
});
So when I click on the "external_btn" button, the "ca" item will be selected on the select2.
But how I can do item unselection? Thanks.
There does not appear to be a built-in function to programmatically deselect/unselect an option from a multiple-select Select2 control. (See this discussion.)
But you can get the array of selected values, remove the value from the array, and then give the array back to the control.
Select2 v4:
The following code works for Select2 v4. It also works for Select2 v3 as long as the control is backed by a <select> element, rather than a hidden input element. (Note: When using Select2 v4, the control must be backed by a <select> element.)
var $select = $('#select');
var idToRemove = 'c4';
var values = $select.val();
if (values) {
var i = values.indexOf(idToRemove);
if (i >= 0) {
values.splice(i, 1);
$select.val(values).change();
}
}
JSFiddle for Select2 v4
JSFiddle for Select2 v3
Select2 v3:
The following code works for Select2 v3, regardless of whether you back the control with a <select> element or a hidden input element.
var $select = $('#select');
var idToRemove = 'c4';
var values = $select.select2('val'),
i = values.indexOf(idToRemove);
if (i >= 0) {
values.splice(i, 1);
$select.select2('val', values);
}
JSFiddle for Select2 v3, using <select> element
JSFiddle for Select2 v3, using hidden input element
As you've indicated in your question, you can modify the state of the underlying select element and then trigger a change. So then you can simply deselect an option in the same way you might with a regular select.
Assuming an option of value "val", the following code would deselect it:
$("#select option[value=val]").prop("selected", false) // deselect the option
.parent().trigger("change"); // trigger change on the select
http://jsfiddle.net/9fD2N/3/
I don't see anything to "deselect" an element. But, you can get the list of currently selected elements, remove your element and then set the value.
http://jsfiddle.net/wLNxA/
$("#e8_2").select2({
placeholder: "Select a state"
});
$('#removeBtn').click(function () {
// get the list of selected states
var selectedStates = $("#e8_2").select2("val"),
index = selectedStates.indexOf('NV'); // we're removing NV, try to find it in the selected states
if (index > -1) {
// if NV is found, remove it from the array
selectedStates.splice(index, 1);
// and set the value of the select to the rest of the selections
$("#e8_2").select2("val", selectedStates);
};
});
It's works.
$('{SELECTOR}').val('').trigger('change')
If you do not have any other event listener action on select option better :
$("#select2").val("CA").attr('checked', 'checked'); // to check
$("#select2").val("CA").removeAttr('checked'); // to un-check

How can I get dropdown selected value using javascript?

I have an asp.net DropdownList Control. when i use this code
var id = $("[id*='drpCategory'] option:selected").val();
the id is always come first index of dropdown. How can i get other selected values. ?
you can loop through the select elements, please note that using attribute selector alone is too slow, try this:
$("select[id*='drpCategory']").each(function(){
alert(this.value)
})
Try like this:
var values = $("select[id*='drpCategory']").map(function(){
return this.value;
}).get();
and you will have the selected values of all dropdowns.
$("#input_id").click(function(){
var id = $("#drpCategory option:selected").val();
})
jquerys .val() will return the selected value of your drop down, or an array of selected values if the drop down allows multiple.
var selectedItems = $('[id*="drpCategory"]').val();
Docs

Setting the selected options in a multiselect programmatically

I have a multiselect on which I want to select some options on page load. The options will be selected using jQuery or javascript according to values of the options. Those values are stored in a variable as a string - exmaple below. What would be the logic to select those options?
var values = "1,3,5";
here is the example code:
var items = "1,3,5";
$.each(items.split(','), function(idx, val) {
$("select option[value='"+val+"']").attr("selected", "selected");
});
and here's a working example: http://jsfiddle.net/ftte4/

Change a select list display value upon selecting description

I would like a select list that does the following:
When the select list is open, display the list of descriptions.
When the user selects an item, the select list will close an only the value will be displayed.
The reason for this is to conserve space as the values will be much shorter. I'm hoping that there's an answer in jQuery.
Thanks.
Alright, I've worked it out:
$("#selectList").focus(function() {
var selectedOption = $(this).find("option:selected");
selectedOption.text(selectedOption.attr("description"));
});
$("#selectList").change(function() {
var selectedOption = $(this).find("option:selected");
selectedOption.attr("description", selectedOption.text());
selectedOption.text(selectedOption.val());
});
var currSelOption = $("#selectList").find("option:selected");
currSelOption.attr("description", currSelOption .text());
currSelOption.text(currSelOption .val());
It could probably be optimized a bit.

Categories