Harifrais
Harifrais

Reputation: 47

set select2 option using array of text values

I am using select2 for multiselect.I having my array text values. ex:

array = ["a","b"];

I need to select these two after my select2 is loaded. I achieved using a single value but how to achieve the same using an array of values? I am stucking on this.

Question 2:

var values = ["Test", "Prof", "Off"]; // or to take values as array from other document element;
$("#strings").val(values);
$("#strings").trigger('change'); //trigger change for select2 to set values/styles

Using the above i am not able to set selected option in my select2. Note: for this i have used empty multi select

            let long_name = 'a';
            let $element = $('#AGENCY')
            let val = $element.find("option:contains('"+long_name+"')").val()
            $element.val(val).trigger('change.select2');

Upvotes: 0

Views: 873

Answers (1)

Akash prajapati
Akash prajapati

Reputation: 474

Please find the updated code and based on that you can select multiple options:

let $element = $('#AGENCY')
var selectedValues = [];
$.each( ["a","b"], function( key, value ) {
    selectedValues.push($element.find("option:contains('"+value+"')").val());
});
$element.val(selectedValues).trigger('change.select2');

Upvotes: 1

Related Questions