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.

Fathom Analytics $10 discount on your first invoice using this link

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

Sponsor

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.