3

I want to select multiple options in a select2 multivalue control, when clicking a button. This is useful specially for searches where the user needs to select many option to one of the filters

any idea how to achieve it..? I found how to select an option in select2 single option dropdown, but not in a multiselect control for several options at the same time

5

Ok, I found the way. It's just passing an array of option values to 'val' argument:

$('#my_select2').select2('val', ["value1", "value2", "value3"]);
  • an anonymous users just posted this as an alternative solution: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change'); this solution is referenced from select2.org/programmatic-control/… – luciano_s Nov 7 at 16:20
1

you can also do it this way by defining javascript array.

var Values = new Array();
Values.push("value1");
Values.push("value2");
Values.push("value3");

$("#my_select2").val(Values).trigger('change');
-1
var elem = $("#myselect");
var values = ["a", "b", "c", "d", "e"];

multiple selections

var value = ["a", "b", "c"];

single selection

var value = "a";

select function

elem.select2({
    data: values.map(option => ({ selected: value.includes(option), text: option, id: option }))
});
  • Sorry - this answer needs more context/information to make it a complete answer. – HomoTechsual Dec 5 '18 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.