views:

75

answers:

1

I want to use the jquery autocomplete plugin across several input boxes. In order to keep my code DRY I want to tie the autocomplete function to a class and within the autocomplete function pass the id of the field that has called it as an extra parameter. What I am struggling with is obtaining the id of the field that has called the function. Example code of what I am doing is below; can anyone see the problem?

        $(".className").autocomplete('<%=Url.Action("Method", "Controller") %>', {
            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], result: data[i] };
                }
                return rows;
            },
            formatItem: function(row) {
                return row;
            },
            extraParams: {
                extra: function() {
                    var Field1 = $(this).attr('id');
                    var Field2 =  $("#Field1").val();
                    var Field2 =  $("#Field2").val();
                    var Field3 =  $("#Field3").val();
                    return Field1 + "$" + Field2 + "$" + Field3 + "$" + Field4; 
                 }
            },
            delay: 40,
            autofill: true,
            selectFirst: false,
            multiple: false
        });
+2  A: 

Are you sure this is passed to your extraParams function? If not then you can use something like:

$(".className").each(function(){
   var el = $(this);
   .....
       extra: function() {
            var Field1 = el.attr(id);
       }
});

This will allow you to tie each autocomplete to its own specific element.

queen3
@queen3 - I'm not sure if (this) is passed into the extraParams function. Looking at your example I can't see how to tie that in with the autocomplete function (i'm a bit of a jquery newb). Can you provide a bit more detail?
Andy Rose
On the line "var el = $(this)" you _fix_ the variable. Now "el" will be available to all the inner functions regardless of when they're called. Thus, you have access to the element that your .autocomplete is attached to.
queen3
@queen3 - excellent, I just added the el.autocomplete(.... part underneath the variable instantiation and it is all working as expected. Thanks for your help.
Andy Rose