Reputation: 1354
I'm attempting to construct a dynamic URL for a JQuery auto complete widget, but I can't seem to find a way to reference the current element when I am instantiating the widget. $(this) and this reference the HTMLDocument object instead of the element which is currently having the widget instantiated, is there a way of changing this? Here is my code:
$(function()
{
$(".autocomplete").autocomplete({
source: baseUrl+"autocomplete/"+window.filter+"/"+$(this).attr("name"),
minLength: 2
});
}
This is the current URL that is created:
http://example.com/autocomplete/products/undefined?term=test
But it should be:
http://example.com/autocomplete/products/filter-name?term=test
Edit
Here is a JSFiddle
Upvotes: 0
Views: 42
Reputation: 17735
In your code, this
refers to the document object, which doesn't have a name property, hence the error you are seeing.
You need to initialize the autocomplete differently:
var filter = "products";
$(".autocomplete").each(function(i, el) {
$(el).autocomplete({
source: "http://example.com/autocomplete/" + filter + "/" + el.name,
minLength: 2
});
});
And that should work.
Upvotes: 1
Reputation: 32202
You're not inside a different scope, so this
will refer to whatever it was already referring to. You need to loop over each .autocomplete
element:
$(".autocomplete").each(function(i, e) {
//both "e" and "this" now refer to the element
$(e).autocomplete({
source: baseUrl+"autocomplete/"+window.filter+"/"+ $(e).attr("name"),
minLength: 2
});
});
Upvotes: 1