jQuery autocomplete for dynamically created inputs

后端 未结 2 476
小蘑菇
小蘑菇 2020-11-27 05:48

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.

相关标签:
2条回答
  • 2020-11-27 06:08

    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++;
    });
    
    0 讨论(0)
  • 2020-11-27 06:21

    I found that I needed to put teh autocomplete after the append so:

     $tableBody.append(newtr);  
     $('.description', newtr).autocomplete(autocomp_opt);
    
    0 讨论(0)
提交回复
热议问题