jQuery autocomplete not working on dynamically loa

2019-07-28 10:30发布

I am loading an element through jQuery AJAX whose id is 172. Now i want to apply autocomplete on this element. However the following code is not working.

$(document).ready(function(){       
   $( "#172" ).autocomplete({
                minLength: 2,      
                source: function(request, response) {
                    var results = $.ui.autocomplete.filter(jsonCities, request.term);
                    response(results.slice(0, 10));
                },      
                focus: function( event, ui ) 
                {
                    $( "#172" ).val( ui.item.label );        
                    return false;      
                },      
                select: function( event, ui ) {
                    $( "#172" ).val( ui.item.label );        
                    $( "#172-id" ).val( ui.item.value );
                    return false;      
                }    
            });
});

I have observed that this doesnt work for any dynamically loaded element. What am i missing ? Is this the correct way or some other way is there?

标签: jquery
1条回答
你好瞎i
2楼-- · 2019-07-28 10:46

Something like this will work

$.ajax({
url:"..."
type:"...",
success:function(){
    //Add your #172 element and then use autocomplete on it
    $( "#172" ).autocomplete({}) 
}

});

Since your element is not on the DOM when you call the autocomplete function nothing gets the autocomplete behavior, use if after you add the element to the DOM in your Ajax call.

查看更多
登录 后发表回答