Search code examples
jqueryajaxclonebind

JQuery .on() - Cloning Dynamic Content


I am working on a project where a user is able to perform some live search functions. When the results of the live search are displayed, via JQuery Ajax, I need the user to have the ability to click on one of the displayed results and create a clone of that elsewhere on the page. The problem I am finding is since these new live search results aren't processed on the first page load, I consider them to be 'phantom code' that doesn't exist to the DOM. I have done some research on JQuery's on() as well as bind() functions but not sure how I can implement them into my own context.

Here is my JQuery

$(".add").click(function() {
        $(this).parent("li").clone(true).appendTo(".doc_list:first");                       

});

In that snippet (this) refers to my button which exists inside of the LI element (parent) which is dynamically created via the live search results. I need to copy that LI element.

If more code is needed, please let me know.


Solution

  • As your .add button added to DOM after page load ie. dynamically, so you need a delegate event handler (aka live).

    $(".doc_list").on('click', '.add', function() {
        $(this).parent("li").clone(true).appendTo(".doc_list:first");
    });
    

    Here I user .doc_list as container, but if .doc_list also a dynamic element then replace it with some other static element that belong to DOM at page load.