使用jquery为select标签添加值

时间:2016-01-26 13:27:37

标签: jquery jquery-select2 select2

我正在使用select2插件。我正在编写应用程序的基本CRUD操作。当我尝试使用未显示的选定值重新填充选择标记时,我无法理解编辑中的一件事。我这样做是

$.each(p["info"]["recievers_id"] , function(key , value){
    $.each(p["users"] , function(key , nextvalue){
        if (value["$id"] == nextvalue["_id"]["$id"]) {
            myData.push({
                id: nextvalue["_id"]["$id"], 
                text: nextvalue["firstname"]
            });
        }
    });
});

$("#messageTo").select2();
$("#messageTo").select2("data", myData, true); //Build my select
$("#messageTo").trigger('change'); //*1* update the values
//If *1* doesn't works use this lines of code:
//$("#messageTo").select2('destroy');
//$("#messageTo").select2();
//$("#messageTo").select2('data', myData, true );

使用select2插件的select标签

<div class="form-group">
              <select id="messageTo" class="form-control" data-plugin="select2" multiple="multiple"
              data-placeholder="To:">

              </select>
            </div>

有什么我做错了。我试图显示用户在创建时选择的值

  

[对象]

     
    

0:对象

         
      

id:“569dece31dff7b8416004ae3”

             

text:“abc”

    
         

proto :对象

         

长度:1

         

proto :数组[0]

  

1 个答案:

答案 0 :(得分:2)

您可以尝试这种方法:

var myData = []; //My array of objects to populate the select
$.each(p["info"]["recievers_id"] , function(key , value){
 $.each(p["users"] , function(key , nextvalue){
    if (value["$id"] == nextvalue["_id"]["$id"]) {
        myData.push({
            id: nextvalue["_id"]["$id"], 
            text: nextvalue["firstname"]
        }); //push elements one by one           
    }
 });
});

$("#messageTo").select2();
$("#messageTo").select2("data", myData, true); //Build my select2

工作小提琴(更新):https://jsfiddle.net/robertrozas/cnw0q70m/1/

相关问题