How to properly handle “no result” case in jQuery Autocomplete function that the “no result” is not clickable or selectable?
In the “parse” part I add “no result” item:
parse: function(data) {
var array = new Array();
if (!data || data.length == 0) {
array [0] = { data: { Title: "No results" }, value: "No results", result: "No results"};
}
}
So when are there no results, it shows only “No results”. But it is selectable and clickable which is not OK, because this value is then passed to the text input.
EDIT
Complete javascript part:
<script type="text/javascript">
var NoResult= "No result";
$(function() {
$("#txtTextAnimal").autocomplete('<%= Url.Action("Find", "Animal") %>', {
dataType: 'json',
delay: 100,
parse: function(data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i].Title, result: data[i].Title };
}
if (rows.length == 0) {
rows[0] = { data: { Title: NoResult}, value: "", result: NoResult};
}
return rows;
},
formatItem: function(item) {
return item.Title;
}
}).result(function(event, item) {
if (item.Title != NoResult) {
$("#hidAnimalId").val(item.Id);
$("#hidAnimalId").closest("form").submit();
}
});
});
</script>
Im not sure which autocomplete plugin you are using, but there must be a “click” handler somewhere? In this function you could just check the for “No Results”.
Alternatively, could you just set the array value to nothing when there is no data? So…
Updated here:
You can use the result option…This is untested, so some tinkering will probably be needed