正确使用 jQuery select2 的 initSelection 回调与远程数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15174635/
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 14:32:53  来源:igfitidea点击:

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

javascriptjqueryjquery-select2

提问by balteo

I use jQuery select2 plugin in order to retrieve postcodes using the provided ajax callback function as follows:

我使用 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
                        };
                    })
                };
            }
        }
    });
});

Once two postcodes are selected I get the resulting hidden inputin the DOM:

一旦选择了两个邮政编码,我就会hidden input在 DOM 中得到结果:

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

The issue I have is that once the form is redisplayed (for instance in the event of some other controls being in error), the selections (i.e. the two postcodes and especially the text) don't show in the form although the hidden inputdoes have the two values (i.e. 4797 and 4798, which are the ids for the postcode).

我遇到的问题是,一旦重新显示表单(例如,在某些其他控件出错的情况下),选择(即两个邮政编码,尤其是text)不会显示在表单中,尽管hidden input确实有两个值(即 4797 和 4798,它们是id邮政编码的s)。

I am not sure if I have to do another ajax round trip when the form is redisplayed or if there is a better way to go.

我不确定在重新显示表单时是否必须再进行一次 ajax 往返,或者是否有更好的方法。

Can anyone please advise?

任何人都可以请指教吗?

回答by Arun P Johny

The initSelection method has to pass the values which has to be present in the select2

initSelection 方法必须传递必须存在于 select2

Ex:

前任:

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

Demo: Fiddle

演示:小提琴