我一直在尝试创建一个自动完成文本字段。我有一个名为 countryName
的文本框,用户可以在其中输入部分国家/地区名称。显示匹配的国家/地区名称,当用户单击国家/地区名称时,其 ID 应该放置在名为 countryId
的隐藏字段中。
问题是,当选择匹配的国家/地区名称之一时,最后匹配的 ID 会放置在 countryId
字段中,而不是所选项目的 ID。
例如:
在 countryName
文本字段中输入 Ja 可查找以 Ja 开头的所有国家/地区。返回的结果是牙买加 (countryId = 108) 和日本 (countryId = 110)。如果我选择/单击牙买加 - countryId
字段(隐藏字段)中填充的值是 110,而不是 108。
这是我一直在使用的代码。我已经在其他项目中使用过它,但这次找不到什么不同之处以使其行为异常。
var c_id = 0; // countryId
var sp_id = 0; // stateprovinceId
$('#CountryName').autocomplete({
source: function (request, response)
$.ajax({
url: '/Ajax/CountrySearch',
type: 'POST',
dataType: 'json',
data: { param: request.term },
success: function (data) {
response($.map(data, function (item) {
c_id = item.id;
return {
label: item.name,
value: item.name
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
},
select: function () {
event.preventDefault();
alert(countryId);
$('#CountryID').val(c_id);
}
});
如果有第二双眼睛,我们将不胜感激。
最佳答案
$.map
会迭代响应并分配全局c_id
变量- 完成后,
c_id
等于最后一个映射项的id
- 然后您可以使用
$('#CountryID').val(c_id); 在选择事件上分配该值
success
回调中的 修改您的 source返回 item.id
作为值:
response($.map(data, function (item) {
return {
label: item.name,
value: item.id
}
}));
并改变你的方式handle the event利用回调中的参数并获取值
select: function (e, ui) {
e.preventDefault();
$(this).val(ui.item.label);
$('#CountryID').val(ui.item.value);
}
关于jquery - 选择项目时使用 JQuery UI AutoComplete 返回数据集中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388762/