开发者

jQuery UI Autocomplete: return "nothing found" when no search matches occur

开发者 https://www.devze.com 2023-02-06 04:05 出处:网络
Newbie coder here. I have a search bar with jQuery autocomplete, searching through a local json array. When no matches are found, I want to return a string that says \"Nothing found.\"

Newbie coder here. I have a search bar with jQuery autocomplete, searching through a local json array. When no matches are found, I want to return a string that says "Nothing found."

I've tried if statements inside $.grep but nothing has worked so far:

$("#div_name").autocomplete({
  appendTo: ".custom-autocomplete",
  source: function (request, response) {
  var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
  response($.grep(array, function(value) {

  var not_found = 'Nothing found.';

 开发者_如何学JAVA    if (matcher.test(value.value).length && matcher.test(value.nickname).length == 0) {
       return not_found;
     }
     else {
    return matcher.test(value.value)
       || matcher.test(value.nickname);
  }

  }));
},

Thanks for your help!! :)


I think you want to test for 'OR' (||) here:

if (matcher.test(value.value).length && matcher.test(value.nickname).length == 0) {
   return not_found;
 }

will only be true if both value.value AND value.nickname do not have a value. (You haven't shown your data, so I'm guessing here)

 if (matcher.test(value.value).length || matcher.test(value.nickname).length == 0) {
   return not_found;
 }

will match if either is not true, bailing out immediately if value.value does have a length.


You could use _renderItem to render the results how you want. You just need to check here if results are empty and do the return you want.

$("#div_name").autocomplete({
    ...
}).data("autocomplete")._renderItem = function( ul, item ) {
    return "how and where you want to render results";
};
0

精彩评论

暂无评论...
验证码 换一张
取 消