【问题标题】:Proper usage of jQuery select2's initSelection callback with remote data使用远程数据正确使用 jQuery select2 的 initSelection 回调
【发布时间】:2013-02-16 22:50:46
【问题描述】:

我使用 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">

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

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

谁能给点建议?

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    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']);
    

    演示:Fiddle

    【讨论】:

    • 感谢您的回复。嗯...我遇到的问题是,一旦提交并重新显示表单(例如,由于另一个字段出错),我丢失了text 变量(它仍然在服务器端.. .)。你明白我的意思吗?
    • 为什么当多个设置为 false 时这不起作用?当然,您只会使用一个数据对象等。
    • 最后是否必须再次要求这些值?
    • demo 不工作,示例不工作 .. :( 我得到 Uncaught Error: No select2/compat/initSelection
    • select2 资源消失了,这就是演示不起作用的原因,我更新了外部文件,现在可以了jsfiddle.net/VpnCe/675
    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 2013-08-17
    • 2015-05-12
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多