我有一个大型的产品数据库,我使用jQuery .autocomplete()
函数进行搜索。产品正在按名称或ID进行搜索。当出现包含项目的列表时,用户可以从列表中选择一个产品,使用产品ID和其他已知预定义值的其他字段填充输入,例如“税收”或“产品名称”。布局是这样的:jQuery自动完成 - 无论JSON结果还没有准备好,填充输入
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”来选择产品。
有没有什么办法让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);
}
我添加事件监听器来检查聚焦何时或不该做什么:
$(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));
}
});
感谢您的建议,它把我领到了正确的方向,但我仍然不知道如何调用该方法选择结果列表的第一个选项..你知道如何做到这一点? –
将'select'函数中的语句移动到一个单独的函数中,并从'getJSON'回调中调用该函数。 – raduation
它的工作!非常感谢你!我在focusout上添加了一个类,然后移除焦点上的类,并使用jquery自动完成文档来触发来自JSON的响应。请参阅我的编辑:) –