jQuery autocomplete on new element

David Carr

1 min read - 19th Dec, 2017

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.

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.