【发布时间】:2016-11-07 09:58:43
【问题描述】:
我有一个庞大的产品数据库,我通过使用 jQuery .autocomplete() 函数的输入进行搜索。正在按名称或 ID 搜索产品。当包含项目的列表出现时,用户可以从列表中选择一个产品以使用产品 ID 和其他一些具有已知预定义值(如“税”或“产品名称”)的字段填充输入。布局是这样的:
HTML 代码
<input type="text" id="productID" />
<input type="text" id="productName" />
<input type="text" id="quantity" />
<input type="text" id="taxes" />
... and more relative inputs
<input type="text" id="price" />
<!-- add product to cart -->
<input type="submit" value="Add to cart" />
表单的意思是将产品插入到某个购物车中,同时手动填写未知或交替的已知字段。
现在的问题是我通过记忆知道许多产品 ID,并且可以直接输入它们,因此我可以快速调整必要的字段并点击“ENTER”将产品插入购物车。问题是当我离开.autocomplete() 字段时,结果列表消失了,并且没有选择产品。
我的 jQuery
var cache = {};
$("#productID").autocomplete({
minLength: 1,
autoFocus: true,
source: function (request, response) {
var term = request.term; // search-term
// check if the term is already cached
if (term in cache) {
response(cache[ term ]); // return cached result
return;
}
// get results from remote script
$.getJSON("/autocomplete.php", request, function (data) {
cache[ term ] = data; // cache the result for this term
response(data);
});
},
select: function (event, ui) {
// pre-populate fields of the product
$("#productName").val(ui.item.name);
$("#taxes").val(ui.item.taxes);
$("#price").val(ui.item.price);
}
};
在这里,我需要等待响应显示,然后按“TAB”选择产品。
当我在场外“TAB”时,有什么方法可以让 JSON 响应继续,并且它选择列表中的第一项?由于这是非常直接的工作,我不喜欢每次都等待响应显示来选择产品。
编辑
感谢@raduation,找到了解决方案!这是我所做的:
// first altered the autocomplete-select to point to a Js-function
var cache = {};
$("#productID").autocomplete({
minLength: 1,
autoFocus: true,
source: function (request, response) {
var term = request.term; // search-term
// check if the term is already cached
if (term in cache) {
response(cache[ term ]); // return cached result
return;
}
// get results from remote script
$.getJSON("/autocomplete.php", request, function (data) {
cache[ term ] = data; // cache the result for this term
response(data);
});
},
select: function (event, ui) {
// pre-populate fields of the product
selectValueAutocomplete(ui.item, $(this));
}
};
// function to insert item's values in the fields
function selectValueAutocomplete(item, input)
{
input.val(item.value);
$("#productName").val(item.name);
$("#taxes").val(item.taxes);
$("#price").val(item.price);
}
我添加了 Eventlisteners 来检查是否集中注意力时要做什么:
$(document)
.on("focusout", "#productID", function() {
$(this).addClass("selectFirst");
})
.on("focus", "#productID", function() {
$(this).removeClass("selectFirst");
}) // Here I invoke the jQuery.autocomplete()'s response event
.on("autocompleteresponse", "#productID", function( event, ui ) {
if($(this).hasClass("selectFirst"))
{ // select first item from response
selectValueAutocomplete(ui.content[0], $(this));
}
});
【问题讨论】:
标签: javascript jquery json ajax autocomplete