I have this autocomplete
$( "#tags" )
// 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({
minLength: 2,
/*source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},*/
source: function( request, response ) {
$.getJSON( "json.php", {
term: extractLast( request.term )
}, response );
}
/*all the options omitted*/
});
Which works great on dom.ready, but if I dynamically remove and add again the same form, the autosuggest feature wont get enabled, so I thought about using .live() but its giving me the same behavior
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.live( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
/*source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},*/
source: function( request, response ) {
$.getJSON( "json.php", {
term: extractLast( request.term )
}, response );
}
/*all the options omitted*/
});
shouldn’t .live() handle the dom change?
Yes, you should use
on(althoughliveis still available).And you may want to initialize the autocomplete upon the first keystroke:
Note: instead of
$( document ).onit is preferrable to use the closest “#tags” parent which is always in the DOM (never is removed or reloaded).documentis parent of all, and is always present, that’s why it always works foron. But we should avoid attaching all event handlers in thedocument, if possible.Also, what other users answered is correct. When you do:
This is the same as:
It means: the
livecall is not attached to theautocompletecall.Also, as other users answered, instead of the solution above, a better place to initialize the
autocompletewould be in the AJAX success event handler, i.e., right AFTER the “#tags” element is included in the DOM:I hope this helps.