0

I have the following select2:

<select id="e1" multiple style="width: 250px;" name="attributes[]">
    <?php if(isset($vars['attributes'])):?>
        <?php foreach($vars['attributes'] as $attribute):?>
            <option value="<?php echo $attribute['id'];?>"><?php echo $attribute['name'];?></option>
        <?php endforeach;?>
    <?php endif;?>
</select>

Now i load some of the data via. Ajax:

which lists the following array:

enter image description here

Now i wish to add these 3 as selected values to my select2.

How do i do that?

update

HEre is my code so far:

    var _lst = document.getElementById('e1');
var optCount = _lst.options.length;
for (var i=0 ; i<data['attributes'].length; i++){
    var opt = new Option(data['attributes'][i]['name'],data['attributes'][i]['id']);
    _lst.options[optCount+i] = opt;
}

1 Answer 1

1

A very simple way : jsFiddle example

I'm not sure about your attributes type and structure (json ? array ?) You can amend the code for your purpose.

Sign up to request clarification or add additional context in comments.

4 Comments

The picture is taking from the debugger in PHPStorm. however it will be encoded into json
Wait i can see it adds it to the option list but does not set it as selected
it still doesnt add them as selected in your JS fiddle or is mine cached?
if you're ok with this answer, could you please mark it as valid with the green tick ? Many thanks ;)

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.