AnApprentice AnApprentice - 3 months ago 19
jQuery Question

jQuery Autocomplete, how to bind to two input fields?

I would like to bind the the same autocomplete to two input fields.

The fields:

<input id="rwF1" maxlength="250" type="text" value="">
<input id="rwF2" maxlength="250" type="text" value="">


Then my autocompleter in jQuery:

$("#rwF1, #rwF2").autocomplete({
source: availableTags
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $('<li class="roomWizardLI"></li>')
.data( "item.autocomplete", item )
.append( "<a><span class='title'>" + item.value + "</span><span class='Count'>" + "2" + " members</span></a>")
.appendTo( ul );
};


While this binds and the autocomplete menu appears on both inputs. The custom renderItem only applies to the first input field. The second is completely ignored. Any ideas why and how to make the autocomplete work fully for both input fields?

Thanks

Answer

The problem is that .data retrieves data for the first element in the matched elements (according to the documentation).

You'll need to iterate over each item that the autocomplete widget was applied to and apply your custom rendering code:

$("#rwF1, #rwF2").autocomplete({
    source: availableTags
}).each(function () {
    $(this).data( "autocomplete" )._renderItem = function( ul, item ) {
        return $('<li class="roomWizardLI"></li>')
            .data( "item.autocomplete", item )
            .append( "<a><span class='title'>" + item.value + "</span><span class='Count'>" + "2" + " members</span></a>")
            .appendTo( ul );
    };
});

Example: http://jsfiddle.net/kcSfw/