I\'m trying to have a \"No Results\" message appear in the dropdown menu if there are no results. So for instance, if I type in \"ABCD\" into the text field, and there is n
Modify the function like this to check for length of data.
success: function (data) {
if(!data.length){
var result = [
{
label: 'No matches found',
value: response.term
}
];
response(result);
}
else{
// normal response
response($.map(data, function (item) {
return {
label: item.CompanyName + " (" + item.SymbolName + ")",
value: item.CompanyName
}
}));
}
}
My answer is almost identical to @neelmeg and @Trever, but I have added an extra check, so user won't be able to select the "no result" message:
$(".my-textbox").autocomplete({
minLength: 2,
open: function () { $('.ui-autocomplete').css('z-index', 50); },
source: function (request, response) {
$.ajax({
url: "/some-url",
type: "POST",
dataType: "json",
data: { prefix: request.term, __RequestVerificationToken: token },
success: function (data) {
if (!data.length) {
var result = [{ label: "no results", value: response.term }];
response(result);
}
else {
response($.map(data, function (item) {
return { label: item.someLabel, value: item.someValue };
}))
}
}
})
},
select: function (event, ui) {
var label = ui.item.label;
if (label === "no results") {
// this prevents "no results" from being selected
event.preventDefault();
}
else {
/* do something with the selected result */
var url = "some-url"
window.location.href = url;
}
}
});
For me the reason, why this messages occured were:
MISSING CSS FILES O JQUERY UI
so adding:
<link rel="stylesheet" href="jqueryui/themes/flick/jquery-ui.css" type="text/css" media="screen" />
<link rel="stylesheet" href="jqueryui/themes/flick/jquery.ui.theme.css" type="text/css" media="screen" />
solved my problem
if (!ui.content.length) {
var noResult = { value:"",label:"No results found" };
ui.content.push(noResult);
//$("#message").text("No results found");
}
Fiddle
http://jsfiddle.net/J5rVP/129/
Update
Put the code at the end of your auto-complete setup just after select: function (event, ui) {..}
..........
minLength: that.options.minLength,
select: function (event, ui) {
reRenderGrid();
}, //HERE - make sure to add the comma after your select
response: function(event, ui) {
if (!ui.content.length) {
var noResult = { value:"",label:"No results found" };
ui.content.push(noResult);
}
}
});