简体   繁体   中英

How to set selected multiple value of jQuery Select2?

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.

在此处输入图像描述

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM