简体   繁体   English

如何在Select2 jquery中显示多选?

[英]How to display multiple selection in Select2 jquery?

My DB stored information in String like this Administrator,Anna , So if I want to display in Select2 this pre-selection, as I know it is must in Array (Sorry if I am wrong).我的数据库将信息存储在 String 这样的Administrator,Anna ,所以如果我想在 Select2 中显示这个预选,我知道它必须在 Array 中(对不起,如果我错了)。 The problem, I need to split it into Array and display.问题,我需要将其拆分为Array并显示。

Unfortunately, both of the names are not being displayed.不幸的是,这两个名称都没有显示。

在此处输入图片说明

Both of the names already being split in Array.这两个名称都已在 Array 中拆分。

在此处输入图片说明

It appears when the name just is single like this.名字就这样单身的时候就出现了。

在此处输入图片说明

So how to fix it?那么如何修复呢?

JS : JS

$.ajax({
    ...
    success: function(response){
            if (response.status == "Success"){
                $("#editLayer3ActivityOwner").val(response.data[0]["task_owner"]).attr("disabled",false);

                $(response.data).each(function(key,value){
                    var owners = value.task_owner.split(',');
                    $(owners).each(function(k,v){
                        $("#editLayer3ActivityOwner").append($("<option>", {
                            response: v,
                            text: v
                        }));
                    });
                    console.log(owners);
                    $("#editLayer3ActivityOwner").select2();
                });
            }
            else {}       
    },
    error: function(e){}
});

You can use $("#sel").val(["Administrator","Anna"]).change();您可以使用$("#sel").val(["Administrator","Anna"]).change(); method.方法。 i think you are getting response in the same format.so you can give response directly as $("#editLayer3ActivityOwner").val(response.data).change();我认为你得到的响应$("#editLayer3ActivityOwner").val(response.data).change();相同。所以你可以直接给出响应$("#editLayer3ActivityOwner").val(response.data).change();

 $("#editLayer3ActivityOwner").select2({ width: '100%', placeholder: "Choose", allowClear: true }); var response=["Administrator","Anna"]; //Hope you are getting the ajax response as this $("#editLayer3ActivityOwner").val(response).change();
 <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.min.js"></script> <select id="editLayer3ActivityOwner" multiple name="editLayer3ActivityOwner"> <option value="Administrator">Administrator</option> <option value="Anna">Anna</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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