【问题标题】:Removing selected item in select2 not updating val()删除 select2 中的选定项目不更新 val()
【发布时间】:2020-01-30 07:16:37
【问题描述】:

我有一个使用多选 select2 的输入控件

 <input class="form-control no-padding cTagID" tabindex="3" id="cTagID" name="cTagID" style="border:none;" />

我将其转换为 select2 并从 ajax 获取数据,如下所示

 $("#cTagID").select2({
            placeholder: "Select a Tag",
            allowClear: true,
            width: '100%',
            multiple: true,
            maximumSelectionSize: 9,
            escapeMarkup: function (text) { return text; },
            minimumInputLength: 0,
            ajax: {
                url: '@Url.Action("myaction", "mycontroller")',
                dataType: 'json',
                quietMillis: 0,
                cache: false,
                type: "POST",
                data: function (term, page) {
                    return {
                        q: term,
                        page: page,
                        listType: "mytype",
                        Searchterms: $("#iProjectId").val()
                    };
                },
                results: function (data, page) {
                    var more = (page * 30) < data.total_count; // whether or not there are more results available
                    return {
                        results: $.map(data.items, function (item) {
                            return {
                                text: item.text,
                                id: item.id
                            }
                        }),
                        more: more
                    }
                },
                cache: true
            }
        }).on("change", function () {

            $(this).valid();
            alert($("#cTagID").val()) // Problem is here ..Even if a selected item is removed by user it will still be available in val
        });

Ajax 调用过滤器和分页等工作正常,我得到以下格式的数据

{ 
   "total_count":6905,
   "items":[ 
      { 
         "id":"(DB-227)-Q14-SL03        ",
         "text":"(DB-227)-Q14-SL03         ~ E_ELOOP                  "
      },
      { 
         "id":"(DB-227)-Q14-SL04        ",
         "text":"(DB-227)-Q14-SL04         ~ E_ELOOP                  "
      },
      { 
         "id":"011100-727               ",
         "text":"011100-727                ~ E_OTP                    "
      },

   ]
}

问题是如果用户选择一个项目然后将其删除,它将保留为 val ("#cTagID").val() 也会返回已删除的项目

【问题讨论】:

  • 看看网址:select2.org/programmatic-control/…。添加“$(this).trigger('change');”在语句“$(this).valid();”之后然后在尝试获取下拉列表的值之后。它应该可以工作。

标签: jquery ajax jquery-select2


【解决方案1】:

在研究了 Select2.js 脚本之后。我发现 select2 在显示所选项目时会修剪 id 字段。但是值仍然未修剪。因此,当删除选定的项目时,select2 会尝试删除带有修剪 id 的项目。但不会找到它,因为它与任何值都不匹配。

注意:如果在分配给 select2 之前的字符串,则最好在数据源中为 Id 使用修剪值

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多