JQuery UI Autocomplete: return "nothing found" when a search match does not occur

The newbie coder is here. I have a jQuery autocomplete search bar that is looking for a local json array. When no matches are found, I want to return a string that says "nothing was found."

I tried if the statements are inside $ .grep, but nothing has been working 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.'; 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 the help!:)

+4
source share
2 answers

I think you want to check here "OR" ( || ):

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

will be true only if both value.value AND value.nickname do not matter. (You did not provide your details, so I assume here)

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

will match if it is not, immediately if value.value has a length.

0
source

You can use _renderItem to render the results as you want. You just need to check here if the results are empty and perform the required return.

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

Source: https://habr.com/ru/post/1336227/


All Articles