簡體   English   中英

在select2 multiselect中加載值

[英]Load values in select2 multiselect

我用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. 

}

請查看Loading 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'}
]

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

此技巧會加載選擇框中的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM