Roch
Roch

Reputation: 22041

JQuery Autocomplete on Ajax loaded content

I would like to use the JQuery's autocomplete plugin on a input box loaded using Ajax:

I have tried to achieve that using the following code, however it only works when the users clicks twice into the input :

$(document).ready(function() {
    $('#auto').live('keydown', function(){
        $(this).autocomplete(
          "/autocomplete",
          {
            delay:10,
            minChars:2,
            matchSubset:1,
            matchContains:1,
            cacheLength:10,
            onItemSelect:selectItem,
            onFindValue:selectItem,
            formatItem:formatItem,
            autoFill:true
        });
    });
});

Could you tell me if there is something wrong with my code?

Thanks,

Upvotes: 3

Views: 3957

Answers (3)

George Mamaladze
George Mamaladze

Reputation: 7931

The solution given in question had one issue. It executes auto-complete only after second character, because the first character can not be used for auto-complete query, thus this is the one which triggers keydown and executes registration of the control for auto-complete.

Following code attaches to all (matching) existing and newly created (Ajax) element's focus event, and performs autocomplete() registration after you click or tab into the input:

$(document).delegate(":input[data-autocomplete]", "focus", function() {
    $(this).autocomplete({
        source: $(this).attr("data-autocomplete"),
    });
})

in this example the selector find all elements having attribute "data-autocomplete", the same attribute is used as source url:

<input id="1" data-autocomplete="++URL++">

Importarnt: Depending on version you could use either live(), delegate() or on() function at the first place. Signatures of these three are slightly different, but it's quite easy to figure out how they map to each other:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

Upvotes: 3

Prasad-PHP Champ
Prasad-PHP Champ

Reputation: 59

$('#auto').live('keydown', function(){

    $( "#auto" ).autocomplete({
    source: data,
    minLength: 3
    });

});

Above worked for me...

Upvotes: 1

johnhaggkvist
johnhaggkvist

Reputation: 354

I'm not sure, but I think the live()-function in your example will bind the keydown-event so that it applies the autocomplete only after you've triggered it. Try skipping the live() and go with only the autocomplete:

$(document).ready(function() {
    $('#auto').autocomplete(
       "/autocomplete",
       {
            delay:10,
            minChars:2,
            matchSubset:1,
            matchContains:1,
            cacheLength:10,
            onItemSelect:selectItem,
            onFindValue:selectItem,
            formatItem:formatItem,
            autoFill:true
       }
    );
});

Upvotes: 0

Related Questions