我试图从jquery自动完成中获取所选值,因为某些原因我无法获取id。我在这里看到了一个解决方案http://www.codeproject.com/Articles/152558/jQuery-UI-Autocomplete-with-ID,但我的数据返回如下所示我应该如何保存ID?
我的数据
[{"id":3,"homename":"DCosta"}]
我的代码
$("#lastname").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.ajax({
type: 'POST',
url: someurl,
dataType: 'json',
data: { "Name": request.term},
success: function (result) {
var Surnames = JSON.parse(result.data);
cache[term] = ($.map(Surnames, function (item) {
return {
label: item.homename,
//value: item.id //<== if I do like this the id show in the text box which I do now want
value: item.homename //<== this shows correctly but the id is not accessable
}
}));
response(cache[term]);
},
error: function (a, b, c) {
debugger;
}
});
},
select: function (event, ui) {
self.Surname(ui.item.value); // save selected value
console.log(self.Surname()); // shows ID if value: item.id or just the name
},
minLength: 2
});
答案 0 :(得分:1)
您可以添加一个隐藏字段来存储您的id
(让我们为myhiddenid
添加ID),并将自动填充字段的值设置为从您的标签返回的标签功能。添加return false;
将取消事件的默认行为
默认操作是将文本字段的值替换为所选项的值。
var myhiddenid = $("#myhiddenid");
var lastname = $("#lastname");
lastname.autocomplete({
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.ajax({
type: 'POST',
url: someurl,
dataType: 'json',
data: { "Name": request.term},
success: function (result) {
var Surnames = JSON.parse(result.data);
cache[term] = ($.map(Surnames, function (item) {
return {
label: item.homename,
value: item.id
}
}));
response(cache[term]);
},
error: function (a, b, c) {
debugger;
}
});
},
focus: function (event, ui) {
lastname.val(ui.item.label);
myhiddenid.val(ui.item.value);
return false;
},
select: function (event, ui) {
lastname.val(ui.item.label);
myhiddenid.val(ui.item.value);
self.Surname(ui.item.value);
console.log(self.Surname());
return false;
},
minLength: 2
});