Search code examples
jqueryclone

jQuery's .clone(true, true) not cloning event bindings on children


I'm using clone(true, true) to copy a select and some buttons to clone and remove. I thought the second true argument should ensure that the event handler is passed on to the cloned child buttons.

Here is the markup:

<div id="clone-container">
    <div class="clone">
        <label for="select1">Select 1</label>
        <select id="select1" name="select1" class="">
            <option>Select One:</option>
            <option value="1">1</option>
        </select>
        <span class="controls">
            <a href="#" class="btn add">+</a>
            <a href="#" class="btn remove">−</a>
        </span>
    </div>
</div>​

And the js:

var $cloned = $('.clone').clone(true, true);
var $addButton = $(".btn.add");
$addButton.on("click", function(e) {
    e.preventDefault();
    var $cloner = $(this).closest(".clone");    
    $cloned.clone().insertAfter($cloner);
});​

And here is a js fiddle: http://jsfiddle.net/cjmemay/yXA4R/


Solution

  • There are two problems with your code:

    1. The original clone ($cloned) does not have an event listener bound to the button
    2. Your second invocation of clone does not preserve events

    You need to clone the container after you have attached the event listener to the button. Additionally, you need to pass the true arguments to the second invocation of clone:

    var $addButton = $(".btn.add");
    $addButton.on("click", function(e) {
        e.preventDefault();
        var $cloner = $(this).closest(".clone");    
        $cloned.clone(true, true).insertAfter($cloner);
    });
    var $cloned = $('.clone').clone(true, true);
    

    Here is a demonstration: http://jsfiddle.net/3hjfj/