JQuery AutoComplete and Clone

僤鯓⒐⒋嵵緔 提交于 2019-12-04 05:30:37

This is a common issue using plugins on dynamically added elements. It usually requires calling the plugin on the new elements after they are inserted in the DOM. Instead of duplicating the same code for the initial page load elements and new elements, you can usually create a simple helper function that uses a parent element as the main reference and searches only within that element for the elements to apply the plugin to.

Important: You are repeating ID's when you clone new rows and ID's must be unique in a page by definition. The following code changes your ID's to class instead and you will need to do same in your markup.

var $table;
$(function() {
     $table=$('#myTable'); 
     var $existRow=$table.find('tr').eq(1);
      /* bind to existing elements on page load*/
      bindAutoComplete($existRow);
});

function addRow(){
    var $row=$table.find('tr:last').clone(true);
    var $input=$row.find('input').val("");
    $table.append($row);
    bindAutoComplete($row );
    $input.focus();

}


function bindAutoComplete($row ){
    /* use row as main element to save traversing back up from input*/
    $row.find(".product_title").autocomplete(products, {
        width: 380,
        matchContains: "word",
        formatItem: function(row) {
            return row.title;
        }
    });
    $row.find('.product_title').result(function(event, data) {
        $row.find('.product_description').val(data.description);
    });
}

I think the problem is, with clone(), you clone an element, which already have the autocomplete properties and then autocomplete can't add "again" to the new element. I think you should not clone(), you should use the original HTML code of the element and put it in.

EDIT:

How I fixed it:

  1. autocomplete("destroy") for the orginal input field you would like to clone.
  2. Clone your element and add the autocomplete to it

And don't use clone(true), but you can use clone()

mckeegan375

Charlietfl's post solved my problem, the only change I had to make was replacing:

var $row=$table.find('tr:last').clone(true);

with

var $row=$table.find('tr:last').clone();removing the true.

Hope this helps somebody else :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!