Dreamer
Dreamer

Reputation: 7551

jQuery.clone(false) still copy data from original source

This post is a follow up with previous post, the application is running on jQuery 1.4 but advice from any version is appreciated:

Current problem is even use

rowTemplate = j('.form-denomination:first-child').clone();

and

var newRow = rowTemplate.clone().attr('id', newRowId);

I can see newRow still holds the old data in first child from the list using firebug, no matter what I select from web page.

For example, if the first child for the list to be cloned is node[0]

<select id="_denominations[0].id.denominationId" class="removableDenom" name="denominations[0].id.denominationId">
    <option value="100">100</option>
    <option value="1000">1000</option>
    <option value="10000">10000</option>
    <option value="500">500</option>
    <option value="5000">5000</option>
    <option value="50000" selected="selected">50000</option>
</select>

And I add a new row after node[2], it would look like

<select id="_denominations[3].id.denominationId" class="removableDenom" name="denominations[3].id.denominationId">
    <option value="100">100</option>
    <option value="1000">1000</option>
    <option value="10000">10000</option>
    <option value="500">500</option>
    <option value="5000">5000</option>
    <option value="50000" selected="selected">50000</option>
</select>

See it is still showing 50000 as selection for the dropdown box, even it shows 100 on the webpage So what's going on?

Upvotes: 0

Views: 1400

Answers (2)

MattW
MattW

Reputation: 4628

You're asking more of .clone() than it's able to give, I'm afraid. It will not update ids for you; it will not update names for you; it will not clear out form data for you. You're going to have to do all of these things yourself - the form data you can clear on the template, but the ids you'll have to set when you do the insert.

rowTemplate = j('.form-denomination:first-child').clone();
rowTemplate.find("input[value], textarea").val("");
rowTemplate.find("select").each(function() { this.selectedIndex = 0; });

If we're able to assume that the first row will always have ids and names that are like [0], the update prior to insert will be a little easier:

var rowId = "[" + j('.form-denomination').length + "]";
var newRow = rowTemplate.clone();
newRow.find("[id]").each(function() { var $t = $(this); $t.attr("id", $t.attr("id").replace("[0]", rowId)); });
newRow.find("[name]").each(function() { var $t = $(this); $t.attr("name", $t.attr("name").replace("[0]", rowId)); });

Upvotes: 1

a better oliver
a better oliver

Reputation: 26828

"it is still show 50000 as selection for the dropdown box, even it shows 100 on the webpage"

What you see is the HTML source. 50000 is not the current value shown on the page, but the value that is (or rather would be in this case) shown when the page has loaded.

Upvotes: 3

Related Questions