I have a form where I want to be able to duplicate a group of fields as many times as I want. And I also want to have field id, name, and label\'s
Here's my version.
http://jsfiddle.net/Unfxn/27/
It relies heavily on the index of the repeating region. So don't add any siblings above it. If you do need that, then wrap all repeating regions in another div.
Damn! too late :) anyway... here's the code.
// Add a new repeating section
var attrs = ['for', 'id', 'name'];
function resetAttributeNames(section) {
var tags = section.find('input, label'), idx = section.index();
tags.each(function() {
var $this = $(this);
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx + 1)))
}
})
})
}
$('.addFight').click(function(e){
e.preventDefault();
var lastRepeatingGroup = $('.repeatingSection').last();
var cloned = lastRepeatingGroup.clone(true)
cloned.insertAfter(lastRepeatingGroup);
resetAttributeNames(cloned)
});
// Delete a repeating section
$('.deleteFight').click(function(e){
e.preventDefault();
var current_fight = $(this).parent('div');
var other_fights = current_fight.siblings('.repeatingSection');
if (other_fights.length === 0) {
alert("You should atleast have one fight");
return;
}
current_fight.slideUp('slow', function() {
current_fight.remove();
// reset fight indexes
other_fights.each(function() {
resetAttributeNames($(this));
})
})
});