Reputation: 1965
I have a MVC application which is using the autocomplete as in link 1. Then, to be able to format the display, I have passed a complex JSON object with this JSON schema:
{
"name": "searchResults",
"properties": {
"Id": {
"type": "number",
"description": "Table.ID, maps to value",
"required": true
},
"Name": {
"type": "string",
"description": "Display name, maps to label",
"required": true
},
"Type": {
"type": "number",
"description": "Table selector (enum)",
"required": true
}
}
}
The problem is that I cannot use $(this)
inside the $.ajax
function. I tried using context, but it is not working. I keep receiving "SyntaxError: Unexpected token <". Here is the JavaScript code:
$(function () {
$('*[data-autocomplete-url]').each(function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
// THIS WORKS!
//url: $('*[data-autocomplete-url]').data('autocomplete-url'),
// THIS DOESN'T WORK!
url: $(this).data('autocomplete-url'),
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
token: $("#tags").val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
select: function (event, ui) {
$("#tags").val(ui.item.label);
$("#tagsId").val(ui.item.value);
event.preventDefault();
},
focus: function (event, ui) {
$("#tags").val(ui.item.label);
event.preventDefault();
},
minLength: 3
});
});
});
Here is the Razor snippet:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" data-autocomplete-url="@Url.Action("Search", "Search")" />
<input id="tagsId" hidden="hidden" />
</div>
Is there a way to use $(this)
to get the specific autocomplete element responsible for firing the action?
References:
ASP.NET MVC & jQuery UI autocomplete
Upvotes: 1
Views: 596
Reputation: 62488
in ajax function this
not works, as it does not have scope to the reference of the element.
you need to store a copy of this before making the ajax request:
var url = $(this).data('autocomplete-url');
and in ajax call use that variable:
url:url
Upvotes: 2
Reputation: 74420
Use a closure variable inside each
loop or get element using inside source
callback method:
url: $(this.element).data('autocomplete-url'),
Upvotes: 1