【发布时间】: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