HM2K
HM2K

Reputation: 1511

How do you clone events and data to clone but apply to the newest clone?

You can clone an element with it's events and data, but then the events still apply to the original object instead of the new object.

I have used jsfiddle to demonstrate the issue: http://jsfiddle.net/VZZG4/

To reproduce: 1. Hit the clone button 2. In the new text input, type "New" 3. Hit the new clone button Actual result: The newest clone says "Test" Expected result: The newest clone says "New"

Question: How do you clone events and data to clone but apply to the newest clone?

Upvotes: 0

Views: 459

Answers (2)

Felix Kling
Felix Kling

Reputation: 816404

You make the mistake to clone objects with IDs. In most browser, if you have several elements with the same ID, the first one will be returned. Thus $('#container') will always return the first one with the value Test.

Give the elements that should be cloned classes instead.

HTML:

<div id="wrap">
    <div class="container">
        <input type="text" class="edit" value="Test">
        <input type="button" class="clone" value="Clone">
    </div>
</div>

JavaScript:

$(document).ready(function() {
    $('.clone').click(function() {
        $(this).closest('.container').clone(true).appendTo('#wrap');
    });
});

Check the modified version of your code http://jsfiddle.net/VZZG4/2/

Reference: closest

Upvotes: 2

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

use closest() to clone the expected element...

$(document).ready(function() {
    $('#clone').click(function() {
        $(this).closest('#container').clone(true).appendTo('#wrap');
    });
});

updated fiddle

and I suggest for you to use class instead of an id. Duplicate id is not valid html.

Upvotes: 2

Related Questions