How to set selected multiple value of jQuery Select2?

Viewed 55

Try to set selected multiple value of select option. But error when try to add another option

    <select id="flag" class="flag" name="flag[]" multiple="multiple" class="form-control" style="width: 100%">
    </select>

JS

     var data="[";
                for (var i=0;i<5;i++){
                    data+="{\"id\":\""+i+"\",";
                    data+="\"text\":\""+i+"\"}";
                
                    if(i<4){
                        data+=",";
                    }
                }
                data+="]";
                data = JSON.parse(data);
            
              
                $('.flag').select2({
                    data:data
                });


  $('#flag').val([1,2]);
  $('#flag').trigger('change');

Try to set it with script above. The value in the select input field is run correctly like image below.

enter image description here

But as you can see, number 1 and 2 is not selected in dropdown option. So, when i try to click option "3". I expect it will shows 1,2,3. But the output is only "3", "1" and "2" is disappear.

Is it how it's done or am i missing something?

Currently using select2 v4

1 Answers

It run correct, you need check css of you

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Color Changer</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    </head>
    <body>
        <select id="flag" class="flag" name="flag[]" multiple="multiple" class="form-control" style="width: 100%">
        </select>
        <button id="test">trigger</button>
        <script>
        $(document).ready(function() {
            const data = [
                {
                    id: 0,
                    text: 'enhancement'
                },
                {
                    id: 1,
                    text: 'bug'
                },
                {
                    id: 2,
                    text: 'duplicate'
                },
                {
                    id: 3,
                    text: 'invalid'
                },
                {
                    id: 4,
                    text: 'wontfix'
                }
            ];
            $('#flag').select2({
                data: data
            });
            $("#test").click(function() {
                $('#flag').val([1, 2]).trigger('change');
            });
        });
        </script>
    </body>
    </html>

Related