Javascript | Tutorials

David Carr

jQuery autocomplete on new element

jQuery’s autocomplete plugin is perfect for filling in forms with suggestions as you type in an input field. If you’ve ever added dynamic inputs you may have noticed the autocomplete does not work when using a call like this:

$(".product").autocomplete({
    source: '/products/search',
    minLength: 1,
    select: function(event, ui) {
        //update input with selection
        $(event.target).val(ui.item.value);
    }
});

The problem is the call to autocomplete happens on page load so adding inputs dynamically won’t pick up the autocomplete call instead add the autocomplete on to an on click event instead like this:

$('body').on('click', '.product', function() {
    $(this).autocomplete({
        source: '/products/search',
        minLength: 1,
        select: function(event, ui) {
            //update input with selection
            $(event.target).val(ui.item.value);
        }
    });
});

This will cause the autocomplete to only trigger when clicking on an input.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2020 DC Blog. All code MIT license. All rights reserved.