GeekyNuns GeekyNuns - 6 months ago 20
jQuery Question

Autocomplete show all values

I have a struggle showing all possible autocomplete rows.
I`m using db to store all the rows.
Now I use that script :

<script type="text/javascript">

$(document).ready(function () {
$("#Industry").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Employee/SuggestWorkExperienceIndustry",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Industry, value: item.Industry };
}))

}
})
},
messages: {
noResults: "failure", results: ""
}
});
});
</script>


Controller part :

[HttpPost]
public JsonResult SuggestWorkExperienceIndustry(string Prefix)
{
using (var db = new HRMEntities())
{
var industryList = db.WorkExperienceIndustries.ToList();

var industry = (from n in industryList
where n.Industry.ToLower().Contains(Prefix.ToLower())
select new { n.Industry });

return Json(industry, JsonRequestBehavior.AllowGet);
}
}


It works well, but i cant get the idea how to get all the rows from the db when user clicks on field.

Answer

There is a property in autocomplete widget minLength, which has a default set at 1. Which means you need to enter at least one character in the textbox before it starts requesting for data. Set it to 0 and it should load the whole list right away:

minLength: 0

But be very sure this is the behavior you really want, because it will indeed load all your items. Might not be very user friendly.

Update. It seems there is no built-in way to trigger search just on focus though. But it is really simple to trigger it manually:

$("#Industry").autocomplete({
    source: ...
    messages: ...
    minLength: 0
}).focus(function () {
    $(this).autocomplete("search");
});