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


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

$('#my_select2').select2('val', ["value1", "value2", "value3"]);
| improve this answer | |
  • 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 '19 at 16:20

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

var Values = new Array();

| improve this answer | |
var elem = $("#myselect");
var values = ["a", "b", "c", "d", "e"];

multiple selections

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

single selection

var value = "a";

select function

    data: values.map(option => ({ selected: value.includes(option), text: option, id: option }))
| improve this answer | |
  • 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.