I wrote code that could not use jQuery autocomplete to run the result function after the user selects something real (below).
As a result, I mean the result handler, a function that fires after a good selection occurs in the autocomplete plugin. Documented here .
In my case, I have a form that is really a table, where each row is the same, minus the unique identifiers of the fields: Item1, Qty1, Desc1, then Item2, Qty2, Desc2, etc. When the user enters the code Item1, the text Desc1 should display the English code of the selected item (Item2 → Desc2, etc.).
I used this code to find all the inputs of an Item and autocomplete it. For some reason, the result event handler does not fire. If you noticed, I hardcoded the selection of “Item1” because I did not understand how to select the appropriate Desc for the item, where Item1 → Desc1, Item2 → Desc2, etc.
I used MVC Url.Content only because I managed to get it to work. Someone used Url.Action, which, I think, is better, you just need to understand this.
Feel free to fix my use as needed, this is my first time with ASP.NET MVC / JQuery.
Thanks:)
Code:
$(document).ready(function(){
$("input[id^='Item']").autocomplete( "<%= Url.Content("~/products/autocomplete")%>", {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for( var i = 0; i<data.length; i++)
{ rows[i] = {data:data[i], value:data[i].name, result:data[i].id }; }
return rows;
},
formatItem: function(row, i, n) {
return row.id + ' - ' + row.name;
},
selectFirst: true,
minChars: 2,
max: 30,
autoFill: true,
mustMatch: true,
matchContains: false,
scrollHeight: 100,
width: 300,
cacheLength: 1,
scroll: true
});
$("Item1").result(function(event, data, formatted) {
$("Desc1").html( !data ? "No match!" : "Selected: " + formatted);
});
});