我在一个页面上有2个自动完成,它搜索sql数据库并将结果显示到输入字段中。拳头自动完成效果很好。第二个需要传递client_id,因为它根据第一个搜索的客户端ID搜索sql。此外,我希望第二个自动完成在用户单击框内时立即显示所有结果。这是我的代码。
$( "#client_name" ).autocomplete(
{
source:'ls_billto_client_name.php',
minLength: 0,
select: function(event, ui){
$("#client_id").val(ui.item.client_id)
$("#client_name").val(ui.item.label)
$("#shipto_id").val(ui.item.client_default_shipto_id)
$('#shipto_name').prop('disabled', false);
}
})
$( "#shipto_name" ).autocomplete(
{
source: 'ls_shipto_locations.php?client_id='+ $("#client_id").val(),
minLength: 0,
select: function(event, ui){
$("#shipto_id").val(ui.item.shipto_id)
$("#shipto_name").val(ui.item.label)
$("#shipto_street").val(ui.item.shipto_street)
$("#shipto_city").val(ui.item.shipto_city)
$("#shipto_stateprov").val(ui.item.shipto_stateprov)
$("#shipto_country").val(ui.item.shipto_country)
$("#shipto_postalzip").val(ui.item.shipto_postalzip)
$("#shipto_phone").val(ui.item.shipto_phone)
$("#shipto_fax").val(ui.item.shipto_fax)
$("#shipto_website").val(ui.item.shipto_website)
}
})
答案 0 :(得分:0)
问题是当您在autocomplete
上实例化$('#shipto_name')
时,它不是动态的。它会立即占用该值以填充该字段,而您需要向服务器执行ajax请求,作为回报,该请求将为您提供结果。获得这些结果后,您可以将它们映射到源提供的响应回调以创建下拉列表。
$('#shipto_name').autocomplete({
source: function(request, response){
$.ajax({
url:'ls_shipto_locations.php',
type: 'GET',
data: {client_id : request.term},
success: function(data){
response($.map(data, function(obj){ //response is the callback
//considering obj should be JSON with key:value pairs
return{
label: obj.key, //key is the literal key of the object returned
value: obj.key //key is the literal key of the object returned
}
}));
}
});
}
});
现在,shipto将正确查找该文件位置中的客户端ID。我们希望服务器返回的数据是一个JSON编码对象,如下所示:
{label: 'Hello', value: 'World'}
您会在上面的source:
构造中注意到,我们使用request.term
代替$('#client_id').val()
,这更具动态性。让我们看看我们如何使用$('#client_name').autocomplete({ select })
事件来传递我们想要的数据。
$('#client_name').autocomplete({
select: function(event, ui){
//your code
$('#shipto_name').autocomplete('search', ui.item.client_id);
}
});
通过调用自动填充的搜索并传入该术语,我们告诉它执行搜索。 ui.item.client_id
现在将request_term
$('#shipto_name').autocomplete()
提供{{1}}。
这应该是您想要的功能。