views:

29

answers:

2

I'm using the jQuery UI Autocomplete plug-in to make an ajax call and retrieve data. As well as passing the text of the input element I'm trying to pass in the 'id' attribute of the input element as an additional parameter. An extract of my code looks like this -

    $("#autocomplete input").autocomplete({ 
        source: function(request, response) {
            $.ajax({
                url: "search.php",
                dataType: "json",
                data: {
                    term: extractLast(request.term),
                    extra_param: $(this).attr('id')
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.label,
                            value: item.name
                        }
                    }))
                }
            })
        },

    });

The extra parameter is added to the 'data' property in the ajax call. It works okay if I specifically pass in a value e.g. '3' but I want to pass the 'id' attribute of the input element the function is being called on e.g. $(this).attr('id').

I assume it's a problem with 'this' not being evaluated in this part of the code, but I'm at a loss to see how else I can reference the element that is being targeted. Any help appreciated!

+1  A: 
$('#autocomplete input').each(e, function() {
    $(e).autocomplete('/path?param=' + $(e).attr('id'), function() { ... });
});

$('#autocomplete input').each(e, function() {
    $(e).autocomplete({ source:function ... extra_param: $(e).attr('id') ... });
});

There maybe a more elegant way, but, I know autocomplete is somewhat sophisticated. I personally generate the request w/get parameters and use formatItem/formatResult instead of assigning the source to an ajax call.

nessence
Cheers, but having problems with the 1st example. Getting syntax error - 'missing : after property id'. I assume because it's an object...
Phil
Yes, nice catch.
nessence
A: 

I've got it working by breaking the autocomplete call out into an each. This allows me to capture the target element before I execute the autocomplete -

$("#autocomplete input").each(function() {

    var that = this;

    $(that).autocomplete({

        source: function(request, response, this_element) {
            $.ajax({
                url: "search.php",
                dataType: "json",
                data: {
                    term: extractLast(request.term),
                    extra_param: $(that).attr('id')
                }
      ....
Phil