jonH
jonH

Reputation: 43

$(this) in source of jquery autocomplete - why doesn't it work, but the workaround does?

I was having some trouble with the following code. $(this) appeared to be undefined.

$('.version-autocomplete').autocomplete({
    source: '/ajax/versions.json?procedure_name=' + $(this).attr('procedure_name')
})

I found that this works, and I'm wondering why that is. Does anybody know?

$('.version-autocomplete').each(function(i, el) {      
    $(el).autocomplete({
        source : '/ajax/versions.json?procedure_name=' + $(el).attr('procedure_name')
    })  
})  

Upvotes: 0

Views: 74

Answers (1)

Ry-
Ry-

Reputation: 224904

In the second version, you're in an each callback, but in the first, $(this) is evaluated immediately and doesn't point to the element you want. You can also use this properly in the each, by the way:

$('.version-autocomplete').each(function() {      
    $(el).autocomplete({
        source: '/ajax/versions.json?procedure_name=' + $(this).attr('procedure_name')
    });
});

Upvotes: 1

Related Questions