I am trying to setup my Jquery UI autocomplete field to have data from an ajax connection. Here is my code so far:
$("#mainIngredientAutoComplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "../api/IngredientChoices",
dataType: "json",
success: function (data) {
response(function (item) {
return {
label: item.MainName,
value: item.MainItemID
}
});
}
});
}
});
This is my JSON:
[{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}]
HTML:
<table id="tbl_ingredients" style="padding:0px;">
<tr id="ingHeader">
<td>Ingredient</td>
<td>Measurement</td>
<td>Amount</td>
<td><input id="mainIngredientAutoComplete" /></td>
<td></td>
</tr>
</table>
When I start to type "mil" (for milk) my code gives me this error:
EDIT:
I made your change, which worked for a few attempts but now I am getting a new error -
Unhandled exception at line 55, column 25 in [URL]
0x800a1391 - Microsoft JScript runtime error: 'data' is undefined
$("#mainIngredientAutoComplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "../api/IngredientChoices",
dataType: "json",
response: ($.map(data, function(v,i){
return {
label: v.MainName,
value: v.MainItemID
}}))
});
}
});
$.map
instead of pushing the items into a new array yourself. – Rotor