jQuery autocomplete for dynamically created inputs

First you’ll want to store the options for .autocomplete() like :

var autocomp_opt={
         source: function(request, response) {
            $.ajax({
                url: "../../works_search",
                dataType: "json",
                type: "post",
                data: {
                    maxRows: 15,
                    term: request.term
                },
                success: function(data) {
                    response($.map(data.works, function(item) {
                        return {
                                label: item.description,
                                value: item.description
                        }
                    }))
                }
            })
        },
        minLength: 2,
    };

It’s more neat to use the class attribute for marking the input, like:

<input type="text" class="description" name="item[' + i + '][works_description]" />

Last, when you create a new table row apply the .autocomplete() with the options already stored in autocomp_opt:

$('a#add').click(function() {
    var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" class="description" name="item[' + i + '][works_description]" /></td></tr>');
    $('.description', newtr).autocomplete(autocomp_opt);
    $tableBody.append(newtr); 
    i++;
});

Leave a Comment