How to split and display from string to array for Select2 jquery?

大兔子大兔子 提交于 2020-04-11 18:30:35

问题


How to split and display from string to array for Select2 jquery? Current string that I get from DB is like this Michael,Anna,Sofea, hence how to split into array as Select2 format will read array to display the information, like this ["Michael","Anna","Sofea"]

Console.log from API reading

Current console.log after split is like below:

But why the selected that come from DB does not appear in Select2 <select> selection?

<div class="col-lg-10 col-sm-8">
    <select type="text" class="form-control myClass" id="editOwner" multiple="multiple"></select>
</div>

// To read all users fullname from API
$.ajax ({
    ...
    success: function(response){
        for (var i = 0; i < response.data.length; i++) { 
            $("#editOwner").append($("<option>", {
                response: response.data[i].fullname,
                text: response.data[i].fullname
            }));
        }
    }
});

// To read current selected user based on what had been stored from DB
function editLayer3(id){
    $.ajax({
        ...
        success: function(response){            
                if (response.status == "Success"){                    
                    $("#editOwner").val(response.data[0]["task_owner"]).attr("disabled",false);

                    var test = response.data[0]["task_owner"];
                    var results = test.split(",");

                    $("#editOwner").select2();                    
                }
                else {}            
        },
        error: function(e){}
    });

    // Will redirect to Edit form that contain Submit button
}

来源:https://stackoverflow.com/questions/60900754/how-to-split-and-display-from-string-to-array-for-select2-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!