0

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

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

6 Comments

I already mentioned above, Need to select the text field not the val.The code which u gave is to select the val. select2 have id, text. select2.val() means id.
I have updated the answer can you please look into that?
Hi i tried but it only selected the last value in the array,not all values..I need all values to be selected that i pass in the array
s..$("#AGENCY").select2({ placeholder: "Please select an option...", multiple: true, closeOnSelect: false, data: agency_array }); let $element = $('#AGENCY'); $.each( ["default parent account","Agency","Demo ATD","testcaseatd"], function( key, value ) { let val = $element.find("option:contains('"+value+"')").val(); $element.val(val).trigger('change.select2'); });
I have updated code one more time so can you please check it updated code into the answer?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.