簡體   English   中英

正確使用jQuery select2的initSelection回調與遠程數據

[英]Proper usage of jQuery select2's initSelection callback with remote data

我使用jQuery select2插件來使用提供的ajax回調函數檢索郵政編碼,如下所示:

$(document).ready(function() {
    $("#postcodes").select2({
        placeholder : "Search for a postcode",
        multiple : true,
        minimumInputLength : 3,
        ajax : {
            url : "/bignibou/utils/findGeolocationPostcodeByPostcodeStartingWith.json",
            dataType : 'json',
            data : function(term) {
                return {
                    postcode : term
                };
            },
            results : function(data) {
                console.log(data);
                return {
                    results : $.map(data, function(item) {
                        return {
                            id : item.id,
                            text : item.postcode
                        };
                    })
                };
            }
        }
    });
});

一旦選擇了兩個郵政編碼,我就會在DOM中得到hidden input

<input type="hidden" class="bigdrop select2-offscreen" id="postcodes" style="width:600px" name="familyAdvertisement.postcodes" value="4797,4798" tabindex="-1">

我遇到的問題是,一旦重新顯示表單(例如,在某些其他控件出錯的情況下),雖然hidden input確實存在,但選擇(即兩個郵政編碼,尤其是text )不會在表單中顯示有兩個值(即4797和4798,這是郵政編碼的id )。

我不確定如果重新顯示表單或者有更好的方法,我是否必須再做一次ajax往返。

任何人都可以建議嗎?

initSelection方法必須傳遞必須存在於select2

例如:

$("#postcodes").select2({
    placeholder : "Search for a postcode",
    multiple : true,
    minimumInputLength : 1,
    data:[],
    initSelection : function (element, callback) {
        var data = [{id:1,text:'bug'},{id:2,text:'duplicate'}];
        callback(data);
    }
}).select2('val', ['1', '2']);

演示: 小提琴

暫無
暫無

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

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