2

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.

Yuschick
  • 2,642
  • 7
  • 32
  • 45

2 Answers2

3

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.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • 2
    Ideally you want to replace `"body"` with a selector for the nearest parent which is not dynamically loaded. – James Montagne Jun 07 '12 at 16:32
  • That, sir, did the trick. Using it in this context makes it easier for me to understand how and what it achieves. Thank you, very much! – Yuschick Jun 07 '12 at 16:35
  • Actually, this doesn't seem to be holding up in Firefox. – Yuschick Jun 07 '12 at 16:38
  • I don't think I can do a sample in jsFiddle since he dynamic stuff is generated via an ASP page. – Yuschick Jun 07 '12 at 16:47
  • @Yuschick hi mate, you should check again carefully, I think above code should work, instead of `.doc_list` try with `body`, if it resolve the issue – thecodeparadox Jun 07 '12 at 16:56
  • Okay. I really didn't tweak anything. I refreshed a few times and now it works. Odd. But thanks in any event! – Yuschick Jun 07 '12 at 17:08
1
$("Static-container").on('click', '.add', function() {
        $(this).parent("li").clone(true).appendTo(".doc_list:first");                       
});

Where Static-container is a selector to the closest elements that holds all the dynamically added .add elements.

gdoron
  • 147,333
  • 58
  • 291
  • 367