stinkycheeseman
stinkycheeseman

Reputation: 45747

jQuery clone() overwriting previously cloned elements

I have a form template that I need to copy dynamically to associate with new instances of a popup. I'm using jQuery's clone() method to do so. Whenever I try to create a new instance of the template, the previously created forms' options are erased.

Sample code: HTML:

<div id="template" class="modifyDiv">
    <div class="options">
        <label><input type="radio" class="foo" checked="checked" value="bar" name="displayMode">Foo</label>
        <label><input type="radio" class="blah" value="biz" name="displayMode">Blah</label>
    </div>
</div>

JavaScript

popup.create = function() {
    // create popup stuff
    createViewSettings(popup);
}

createTemplate = function(popup) {
...
    var modifyDiv = $("#template").clone(true).removeAttr("id");
    modifyDiv.appendTo($(document.body));
    modifyDiv.data("popup",popup);
    popup.data("settings",modifyDiv);
... }

What's happening is this: when I create a new popup the settings are perfect. But when I create a second one, the original "displayMode" checkbox's value becomes undefined.

I've stepped through and the line that seems to cause the issue is:

var clone = elem.cloneNode(true)

in the clone definition in jquery. I'm using v1.5.1

EDIT: This problem occurs in Chrome 14.0.835.202, but not in IE8 EDIT: This problem occurs when the inputs are radio buttons, not checkboxes.

Upvotes: 0

Views: 601

Answers (2)

Brian Nickel
Brian Nickel

Reputation: 27550

Your answer was partially correct. You can only have one radio group with a given name per <form>, but you can have as many forms as you want on a page. Replacing one of your wrapping <div> elements with a <form> should fix the issue:

<div id="template" class="modifyDiv">
    <form class="options">
        <label><input type="radio" class="foo" checked="checked" value="bar" name="displayMode">Foo</label>
        <label><input type="radio" class="blah" value="biz" name="displayMode">Blah</label>
    </form>
</div>

Live demo: http://fiddle.jshell.net/DfBHh/19/

Upvotes: 2

stinkycheeseman
stinkycheeseman

Reputation: 45747

This is a dumb question; when you clone a div with radio buttons you have to make sure the new div's radio buttons have a unique name, because only one radio button with a given name can be selected on a given page.

Upvotes: 0

Related Questions