【问题标题】:jQuery autocomplete - Fill input regardless if JSON result is not yet readyjQuery 自动完成 - 无论 JSON 结果是否尚未准备好,都填充输入
【发布时间】: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


    【解决方案1】:

    在文本输入字段上添加一个按键事件侦听器,用于侦听 Tab 键。按下 Tab 键后,在文本输入上设置一个属性,表示“使用第一个产品匹配填充”。例如:$('#productId').prop('populateFirst',true);

    然后,在您的 getJSON 回调函数中,检查此属性是否存在,并填充第一个产品。完成此操作后(或者如果出现 ajax 错误),请删除该属性,以免影响下次使用自动完成功能。

    【讨论】:

    • 感谢您的建议,它引导我朝着正确的方向前进,但我仍然不知道如何调用选择列表中第一个选项并显示结果的方法。你知道该怎么做吗?那个?
    • select 函数中的语句移动到一个单独的函数中,并从getJSON 回调中调用该函数。
    • 成功了!非常感谢!我在 focusout 上添加了一个类,并在 focus 上删除了该类,并使用 jquery 自动完成文档来触发来自 JSON 的响应。请参阅我的编辑 :)
    【解决方案2】:

    您为什么不在源选项中简单地指定autocomplete.php 有什么原因吗?

    $("#productID").autocomplete({
        minLength: 1,
        autoFocus: true,
        source: "autocomplete.php"
        },
        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);
        }
    };
    

    编辑

    请参阅this Fiddle.... 它应该可以工作。
    (我模拟了源,当然...但应该可以工作。)

    【讨论】:

    • 我已经尝试过了,但首先我需要提供一个搜索词,并在此基础上收到来自脚本中数据库查询的响应
    • nametaxesprice 还没有在 autocomplete.php 生成的 json 中?
    • 是的,它们是,但它们与来自查询的结果相关。每个产品都有自己的价格和税金设置,所以我需要在数据库中搜索要返回的结果,并且只有那些与该术语匹配的结果。不过,我不太确定您的建议是什么。
    • 你能展示一个 autocomplete.php 生成的 json 的例子吗?看看它的结构?
    • 当我填写像“样本”这样的术语时,JSON 响应将如下所示:[ { "id": "4000001", "value": "4000001", "label": "4000001 - SampleProduct1", "price": "27.75", "name": "Product 1", "taxes": "10%" }, { "id": "4000002", "value": "4000002", "label": "4000002 - SampleProduct2", "price": "12.55", "name": "Product 2", "taxes": "10%" } ]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2016-09-07
    相关资源
    最近更新 更多