Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

jQuery autocomplete on new element

David Carr

Javascript Tutorials

    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.

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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