Reputation: 299
I'm trying to clone a <textarea>
and clone and replace the digit in the label <label> Number 1 <label>
increasing by 1 each time the add button is pressed (So the first label will have Number 1, the label underneath Number 2 etc).
This works with jQuery 1.8 and below but anything above does not clone and add 1 to the digit.
HTML
<div>
<label for="number">Number <span class="one">1</span></label>
<textarea id="number"></textarea>
</div>
<button>Add</button>
jQuery
var $row = $('div').clone(),
cloneCount = 2;
$('button').click(function () {
$row.clone().insertBefore($("button"));
$('span').clone().attr('span', cloneCount++).replaceWith($('[class=one]:last')).text(cloneCount - 1);
});
JSFIDDLE: http://jsfiddle.net/wba6jvkj/
Upvotes: 1
Views: 134
Reputation: 16383
(Answering to this old question, as Google led me here.)
The behavior of .replacewith()
with disconnected nodes has been modified in jQuery 1.9. You may find the following explanation in the replaceWith() documentation (section "Additional Notes"), and also in the jQuery 1.9 upgrade guide:
Prior to jQuery 1.9,
.replaceWith()
would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9,.after()
,.before()
, and.replaceWith()
always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
In your code, you are using .replaceWith()
on a cloned element, thus which hasn't been inserted into the DOM yet.
Upvotes: 0
Reputation: 208002
I don't know what you were attempting with .attr('span'
and why it seemed to work in < 1.8, or why you are subtracting one from cloneCount
, but this should do what you want:
var $row = $('div').clone(),
cloneCount = 2;
$('button').click(function () {
$row.clone().insertBefore($("button"));
$('span.one:last').text(cloneCount++);
});
Upvotes: 2