Setting the selected options in a multiselect programmatically - javascript

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/

Related

Adding multiple fields based on selected values

I am trying to build a simple dropdown where the user can select multiple options and based on the selected options, a corresponding input field will open up. I am using the Chosen jQuery plugin to accomplish this, and used the following JavaScript function to populate the input fields based on selected dropdown values, however it seems to open up only the latest selected value's input field.
To debug this I had created an empty array called selected and appended the chosen dropdown value to it, and then checked if the chosen values were in this array but it still seems to work the same way.
$(document).ready(function(){
var selected = [];
$("select").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");
selected.push(optionValue);
if(selected.includes(optionValue)){
$(".field").not("." + optionValue).hide();
$("." + optionValue).show();
} else{
$(".field").hide();
}
});
}).change();
});

Get select2 selected items using data to prevent sorting

I've doing some research about a problem I'm having with jQuery select2 plugin. The select2 sorts the selected items (no matter which order you choose them) when posting form. I know it may not be a select2 specific bug, but standard html select behaviour.
Now, how could I get the selected items IDs and then put them in a comma separated list in a hidden input so I can respect the order the items were chosen?
$("#formpacint").submit(function (event) {
var data = $('#campoprofesionales').select2('data');
$('#hidprofesionales').val(data);
});
The above code puts the selected items (in the order they were chosen) using its data property, into the hidden input, but the console.log shows them as objects (text+id I guess)..
I'd need to have: 35,14,29 (the ids of selected items as they were selected without sorting)
Thanks
Found a solution
var selections = (JSON.stringify($("#campoprofesionales").select2('data')));
var obj = $.parseJSON(selections);
$.each(obj, function() {
console.log(this.id);
// I here set a hidden field with the ids in the order they were selected
});

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

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

Categories