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.

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.