我有下面的自动补全的jQuery。
<input type="hidden" id="autocompletePid" autocomplete="off" />
相关的JS
<script type="text/javascript">
$(function() {
$("#autocomplete").autocomplete(
{
source : function(request, response) {
$.ajax({
type : 'GET',
url : "/live-search" + '?term=' + request.term,
success : function(data) {
response($.map(data, function(item) {
return {
label : item.street + ' '
+ item.city.city + ', '
+ item.state.stateCode
+ ' '
+ item.zipcode.zipcode,
value : item.pid
}
}));
},
minLength : 3
})
}
});
});
</script>
相关的HTML
<div id="tabs-1" class="ui-tabs-hide">
<input type="text" id="autocomplete" autocomplete="off"
placeholder="Enter an address or city..." /> <input
type="submit" value="GO" />
</div>
我面临的问题是,在当前代码中,该值已更改为pid
,这对用户毫无意义。我添加了一个隐藏的输入,我想更改隐藏的输入的值。
<input type="hidden" id="autocompletePid" autocomplete="off" />
我该怎么做?
答案 0 :(得分:1)
尝试以下代码:
<script type="text/javascript">
$(function() {
//Create a array call 'auto_array'
var auto_array = {};
var label = '';
$("#autocomplete").autocomplete(
{
source : function(request, response) {
$.ajax({
type : 'GET',
url : "/live-search" + '?term=' + request.term,
success : function(data) {
response($.map(data, function(item) {
label = item.street + ' '+ item.city.city + ', '+ item.state.stateCode + ' '+ item.zipcode.zipcode;
//Put the id of label in to auto_array. use the label as key in array
auto_array[label] = item.pid;
return label;
}));
},
})
},
minLength : 3,
//On select the label get the value(id) from auto_array and put in hidden input field 'autocompletePid'
select: function(event, ui) {
console.log(auto_array);
$('#autocompletePid').val(auto_array[ui.item.value]);
}
});
});
</script>
答案 1 :(得分:0)
步骤:
更改返回值以保存pid。将标签和值设置为您显示的值:
var label = item.street + ' '
+ item.city.city + ', '
+ item.state.stateCode
+ ' '
+ item.zipcode.zipcode;
return {
label : label,
value : label,
pid : item.pid
}
通过自动完成绑定到select
功能,根据需要将值设置为其他字段
select: function (event, ui) {
$(autocompletePid).val(ui.item ? ui.item.pid : "");
}
这里是完整的提琴手:https://jsfiddle.net/q9zyejd0/16/。注意:
select
不会触发。您应该手动绑定到change
(当您将焦点移到文本字段之外时,隐藏字段会更新,虽然有点难看,但效果更好),或使用$(autocomplete).focusout
手动修复。 / li>