jqueryjquery-uijquery-ui-autocompletegetjson

jQuery-ui / auto-complete / getJSON - How to pass the id of the element to the external PHP


I'm binding the jQuery-ui autocomplete to more than one element in my page as I want to have autocomplete with the same set of options in different fields. Something like:

<input class='myclass' id='myid1' name='field1' type='text' />
<input class='myclass' id='myid2' name='field2' type='text' />
<input class='myclass' id='myid3' name='field3' type='text' />

I'm using the "Multiple Remote" option from jquery-ui autocomplete, so the javascript looks something like this:

$(".myclass")
    // don't navigate away from the field on tab when selecting an item
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function(event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).data("autocomplete").menu.active) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON("search.php"
                         ,{ term:extractLast(request.term) }
                         ,response);
            },
            search: function() {
                // custom minLength
                var term = extractLast(this.value);
                if (term.length < 1) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });

It all works very nice. But I want to pass the id as a second parameter to getJSON. How can I accomplish this?

I know how to add a second parameter to the $.getJSON statement, but I'm not being able to grab the "id" of the event trigger. I tried $(this).attr('id') but it gave me undefined. Any suggestions?

Thanks.


Solution

  • Be aware that this within the "source" callback is the instance of the plugin, not the INPUT element.

    A reference to the INPUT is actually saved in the plugin instance in the "element" property.
    Do it like this:

    source: function( request, response ) {
         var inputID = this.element.attr('id');
         $.getJSON("search.php"
            ,{ term:extractLast(request.term), id: inputID }
            ,response);
    },