删除 select2 中的选定项目不更新 val()

Removing selected item in select2 not updating val()

我有一个输入控件使用 as multiselection 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                    "
      },

   ]
}

问题是,如果用户 select 一个项目然后删除它,它将保留为 val ("#cTagID")。val() 将 return 删除的项目也

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

N.B :如果它的字符串在分配给 select2

之前,最好在数据源中为 Id 使用修剪值