jquery-ui autocomplete with ASP MVC suggestions not displaying
-
05-10-2019 - |
Question
I have been trying to get a simple example of the jquery-ui autocomplete to work. I have a controller setup to handle the query, and it returns the json that looks to be in order, but I am getting no suggestions showing up.
Here are the js libraries I am including:
<script type="text/javascript" language="javascript" src="/Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" language="javascript" src="/Scripts/jquery-ui-1.8.1.custom.min.js"></script>
<link href="/Content/jquery-ui-1.8.1.custom.css" rel="stylesheet" type="text/css" />
and here is the javascript and the form tags:
<script type="text/javascript">
$(function () {
$("#organization").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Organization/OrganizationLookup',
dataType: "json",
data: {
limit: 12,
q: request.term
}
})
},
minLength: 2
});
});
</script>
<div class="ui-widget">
<label for="organization">Organization: </label>
<input id="organization" />
</div>
I get back a json response that looks reasonable from my controller:
[
{
"id":"Sector A",
"value":"Sector A"
},
{
"id":"Sector B",
"value":"Sector B"
},
{
"id":"Sector C",
"value":"Sector C"
}
]
id and value seem to be the default naming that autocomplete is looking for.
But I get no joy at all. Any thoughts?
Solution
Not the issue here -- you should put css before javascript. Always.
You are not doing anything with the return value. You need to use a callback function to take that data and do something with it. (The "success:" parameter, I believe).
OTHER TIPS
Thanks to Hogan's suggestion, I added the following callback function to the success parameter, and I was good to go:
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
}
}))