【问题标题】:How display error when there is no match using JQuery autocomplete?使用 JQuery 自动完成不匹配时如何显示错误?
【发布时间】:2012-09-05 11:09:03
【问题描述】:

JQuery 有一个很酷的autocomplete function。我想要的是,如果自动完成中没有匹配的条目(例如 zadasdasda 中的用户类型)来向用户标记这一点,因为用户只能在这个特定字段中输入与数据库中一组值中的值匹配的内容。在以某种方式说只使用选项列表之前,有太多可能的条目(> 1,000)。我只是想检查在我自己编写回调之前在 JQuery 中没有任何东西可以执行此操作。我找不到任何东西,只是想仔细检查一下。

谢谢

【问题讨论】:

标签: jquery autocomplete


【解决方案1】:

也许这会有所帮助。如果我了解您的需求,这是一种方法。

在我的例子中,自动完成功能通过 Ajax 从服务器获取数据。

$("#myselect").autocomplete({
  source: function(request, response) {
    $.ajax({
      url: searchUrl,
      dataType: "json",
      data: request,                    
      success: function (data) {
        // No matching result
        if (data.length == 0) {
          alert('No entries found!');
          $("#myselect").autocomplete("close");
        }
        else {
          response(data);
        }
      }});
    },
  dataType: "json",
  autoFill: false,      
  scroll: false,
  minLength: 2,
  cache: false,
  width: 100,
  delay: 500,           
  select: function(event, ui) { 
    //eventuallydosomething(ui.item.value);
    $("#myselect").autocomplete("close");
  } 
});

您感兴趣的部分是从服务器返回数据时:

  success: function (data) {
      // If we get no matching result
      if (data.length == 0) {
        alert('No entries found!');
        $("#myselect").autocomplete("close");
      }

【讨论】:

    【解决方案2】:

    可以将autocomplete._response函数替换为自己的,然后调用默认的jQueryUI函数

    var __response = $.ui.autocomplete.prototype._response;
    $.ui.autocomplete.prototype._response = function(content) {
        __response.apply(this, [content]);
        this.element.trigger("autocompletesearchcomplete", [content]);
    };
    

    然后给autocompletesearchcomplete事件绑定一个事件处理函数(contents是搜索的结果,一个数组):

    $("input").bind("autocompletesearchcomplete", function(event, contents) {
        if(contents.length<1){
         $("#results").html("No Entries Found");
        }
       else{
          $("#results").html("");
       }
    });
    

    DEMO

    Source的例子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-19
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多