【问题标题】:Select2 ajax: preselected data in edit modeSelect2 ajax:在编辑模式下预选数据
【发布时间】:2019-01-17 19:07:47
【问题描述】:

我正在 Laravel 上制作用户个人资料页面,并使用 select2 组件过滤大量项目。

我有一个基于 ajax 的 select2。当你在 /create 页面时很好,但是当我在页面 /edit/1 时,我需要在其中选择值。

$('.search-filter-ajax').select2({
                    width: '100%',
                    minimumInputLength: 3,
                    placeholder: "Search...",
                    ajax: {
                        url: '/api/listing/search/',
                        data: function (term) {

                            return {
                                data: term.term
                            };
                        },
                        processResults: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.name,
                                        search_from: item.name,
                                        model: 'some_model',
                                        id: item.id
                                    }
                                })
                            };
                        },
                        dataType: 'json',
                        type: "GET",
                        delay: 250,
                    },

                });

我尝试使用initSelection 函数,但没有成功,因为当我需要真正的<option value="1"> something </option> 组件时,它只创建select2 文本元素。

initSelection: function (element, callback) {
            var id = $(element).data('select-id');
            var text = $(element).data('select-text');
            callback({ id: id, text: text });
        },

如何在页面加载时在 select2 中有一个有效的预选选项,但仍有机会通过 onChange 触发 ajax 调用?

【问题讨论】:

    标签: javascript jquery laravel jquery-select2


    【解决方案1】:

    好吧,您可以尝试使用自己的逻辑来生成 slect 选项,例如

    $.ajax().then((res)=>{
      $('#select').html('');
        res.data.forEach((item)={$('#select').append($('option').text(item.text).value(item.value);)})
    })
    

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多