3

我已经使用 jquery 函数实现了一个自动完成文本框,并且正在从数据库中获取建议值。一切看起来都很好。

但是,如果没有找到匹配的数据,我想向用户显示一些用户友好的消息“未找到匹配项”并清除文本框。我该如何实施?

添加了当前代码

function txtAutoComplete(acUrl, minLength, txtbxId) {
    $("#" + txtbxId).autocomplete({
        minLength: minLength, 
        source: function (request, responseFn) {
                $.post(acUrl, null, function (resp) {
                var txtValue = $.ui.autocomplete.escapeRegex(request.term);
                var matcher = new RegExp("^" + txtValue, "i");
                var a = $.grep(resp, function (item, index) {
                    return matcher.test(item);
                });
                responseFn(a);
            });
        }

感谢 Yuriy Rozhovetskiy。

var error = 'No match';
if (a.length == 0) {
    responseFn(error);
}
else {
    responseFn(a);
}

但是错误建议是垂直显示的,我怎样才能让它像正常的自动建议一样显示。谢谢

4

3 回答 3

1

您可以在源函数中完成所有这些工作:

source: function (request, responseFn) {
    $.post(acUrl, null, function (resp) {
        var txtValue = $.ui.autocomplete.escapeRegex(request.term);
        var matcher = new RegExp("^" + txtValue, "i");
        var a = $.grep(resp, function (item, index) {
            return matcher.test(item);
        });

        if(a.length == 0){
            alert("No matches found");
            $("#" + txtbxId).val("");
        }
        responseFn(a);
    });
}
于 2013-03-01T08:55:11.440 回答
1

按照 Yuriy Rozhovetskiy 的建议更改了我的代码,几乎没有修改以发送有效的 JSON

var error = ["No match"];
if (a.length == 0) {
    responseFn(error);
}
else {
    responseFn(a);
}
于 2013-03-09T09:53:58.610 回答
0

您可以在返回值的脚本中返回该值。

不要返回任何内容,只需检查您是否有一些值,如果没有返回一个包含“未找到匹配项”值的数组。

于 2013-03-01T08:15:41.640 回答