jQuery 在 select2 多选中加载值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16010455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:11:10  来源:igfitidea点击:

Load values in select2 multiselect

javascriptjqueryjquery-select2

提问by rkj

I'm using select2in place of search box.

我正在使用select2代替搜索框。

Here i'm using to load countries values like this

在这里,我用来加载这样的国家/地区值

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

When i press save button, they are properly submitted to the server, now here the question is when i want to modify the country field after saving to server, how i can load the saved values to the country field.

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

This is how i retrieve data from server

这就是我从服务器检索数据的方式

$.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. 

}

采纳答案by rkj

I just use this http://ivaynberg.github.io/select2/#event_ext_changelink and use the trigger function to load the values

我只是使用这个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");
        } 

This trick load the value in the select box.

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

回答by Subedi Kishor

Please have a look a documentationunder section Loading Remote Data.

请查看部分下的文档Loading Remote Data

You will find and example like:

你会发现和例子如下:

$("#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
          }
});

Also you can do like this:

你也可以这样做:

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

Your JSONdata must be in format like below:

您的JSON数据必须采用如下格式:

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