2013-04-15 44 views
7

我使用select2代替搜索框。在select2多选中加载值

这里我使用的加载这样

$("#countries").select2({ 
    multiple: true, 
    tags:["India", "Japan", "Australia","Singapore"], 
    tokenSeparators: [","] 
}); 

当我按下保存按钮,它们被正确地提交到服务器,现在这里的问题是,当 我想修改该国领域的国家价值观保存到服务器后,我如何将保存的值加载到国家字段。

这是我从服务器获取数据

$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) { 

    //the opts here contains the json values of the countries. 

    //what code should be written here to load the values in $('#countries).select2(); 

    //user can add some more countries or can remove the previously added countries. 

} 

回答

4

我只需使用这个http://ivaynberg.github.io/select2/#event_ext_change链接并使用触发器功能加载值

$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) { 
     parent.parent.parent.showLoader(); 
     if (opts) { 
      $("#countries").val(opts).trigger("change"); 
     } 

这个技巧在选择框中加载值。

+2

我知道这是古老的,所以原谅我,但这似乎不适用于2维数组?我可以加载诸如('dog','cat','mouse')但不是('1':'Dog','2':'Cat','3':'Mouse')的值。你能做到吗? – SBB

8

请看看一个documentationLoading Remote Data

你会发现和例子,如:

$("#e6").select2({ 
    placeholder: "Search for a movie", 
    minimumInputLength: 1, 
    ajax: { 
      // instead of writing the function to execute the request we use Select2's convenient helper 
      url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json" 
      // Other stuffs 
      } 
}); 

你也可以这样做:

$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts){ 
    $("#countries").select2({ 
     data: opts 
    }); 
}) 

JSON数据格式必须是象下面这样:

[{id:0,text:'enhancement'}, 
{id:1,text:'bug'}, 
{id:2,text:'duplicate'}, 
{id:3,text:'invalid'}, 
{id:4,text:'wontfix'} 
] 
+2

我相信从url检索到的数据会加载到用户事件的搜索框中。与用户类型输入一样,值将被检索并选择该值。我想在这里是加载所有从json中检索到的值,而无需任何用户事件。 @Kishor Subedi – rkj

+0

@rohit请检查编辑。 –

+1

感谢@Kishor的帮助,但我发现更简单的方法来做到这一点,我只是使用触发函数来加载值。 – rkj