如何正确显示jquery自动完成中的“无结果”?

时间:2018-11-16 15:22:58

标签: javascript jquery

当用户搜索不在列表中的查询以显示未找到搜索时,我想完成一条消息。我尝试使用

$('#searchTextField').html(" NO SEARCH FOUND");

,但是它不起作用。有谁知道如何用下面的代码解决这个问题?感谢您的帮助。

这是我的代码:

$(function () {
  var myData = [];
   myData.push("NO SEARCH FOUND");
  $.get("http://localhost:8080/myApp/JobSearchItem.xhtml", function (data) {
    $("#searchTextField").autocomplete({
      minLength: 2,
      source: myData,
    }).val('NO SEARCH FOUND').data('autocomplete')._trigger('select');


    $.each(data, function (k, v) {
      myData.push({
        id: v.id,
        label: v.label,
        value: v.id
      });
    });
  });
}); 

html

     <form id="searchForm" >

          <input type="text" name="searchValue" id="searchTextField" class="form-control" 
                           placeholder="search"/>

      <button type="submit"   class="btn btn-primary" >Search</button>   




            </form> 

1 个答案:

答案 0 :(得分:1)

您好,我想您正在寻找是否找不到匹配项,该匹配项应显示在下拉列表中。因此您需要像这样更新代码。

$(function() {
    $("#userInput").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "http://api.stackexchange.com/2.1/users", // update with your url
                data: {
                    site: 'stackoverflow',
                    inname: request.term
                },
                dataType: 'jsonp'
            }).done(function(data) {
                if (data.items) {
                    response($.map(data.items, function(item) {
                        console.log(item);
                        return item.display_name + " " + item.location; // return your value which is coming from ajax response
                    }));
                }
            });
        },
        minLength: 1,
        response: function(event, ui) {
            if (!ui.content.length) {
                var message = { value:"",label:"No results found" };
                ui.content.push(message);
            }
        }
    });
});

<label for="userInput">Search StackOverflow user:</label>
<input id="userInput" type="text" />

请检查工作正常的fiddle