jQuery autocomplete for dynamically created inputs

I'm having an issue using jQuery autocomplete with dynamically created inputs (again created with jQuery). I can't get autocomplete to bind to the new inputs.

Autocomplete

      $("#description").autocomplete({
         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,
    });


New table row with inputs

var i = 1;
var $table = $("#works");
var $tableBody = $("tbody",$table);

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

I'm aware that the problem is due to the content being created after the page has been loaded but I can't figure out how to get around it. I've read several related questions and come across the jQuery live method but I'm still in a jam!

Any advice?


Solution 1:

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++;
});