I have 2 main issues with my clone() script.
- Whenever I clone a div, I’d like to change the text with the increment value. Eg, the new block should have the title “Block 2″… and so on.
- When I click on the radio button and clone it, the cloned block still has the radio selected. I already have the value set to empty value in the script but it does not seem to be working on the first clone.
HTML:
<div>
<div id="mydiv">
<div class="title">Block 1</div>
<div>
<input type="radio" name="blockoption" value="left"> Radio 1<br />
<input type="radio" name="blockoption" value="right"> Radio 2<br />
<select>
<option selected="selected">Select</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select><br />
<input type="text" name="blocktext" />
</div>
</div>
</div>
<input id="addbutton" type="button" value="Add Block" /> <input id="removebutton" type="button" value="Remove Block" />
jQuery:
$("#addbutton").click(function () {
var inc = $('#mydiv').siblings().length;
$('#mydiv:first-child').clone().insertAfter('#mydiv:last-child').find('input').val('');
$('#mydiv').find('.title').each(function() {
$(this).text().replace(/\d+/, inc+2);
});
});
$("#removebutton").click(function () {
var inc = $('#mydiv').siblings().length;
if (inc > 0) {
$('#mydiv:last-child').remove('#mydiv');
$('#mydiv').find('.title').each(function() {
$(this).text().replace(/\d+/, inc-2);
});
}
});
See the code in action here.
Cloning an element that has ID attribute makes your document invalid you can use classes instead. For removing
checkedandselectedproperties you can usepropmethod.http://jsfiddle.net/b7knT/