/* From https://daveismyname.com/duplicate-form-sections-with-jquery-bp and http://www.philippecloutier.com/blogpost47-Duplicate-form-sections-with-jQuery-Improved * MIT License * Depends on jQuery * May be used with numberedParametersToArrays() **/ //define template var template = $('#sections .section:first').clone(); //define counter var sectionsCount = jQuery('div.section:last').data('number'); function incrementIdentifier(id, sectionsCount) { if (id.substr(-1) == '0') { id = id.substr(0, id.length - 1); } return id + sectionsCount; } //add new section $('body').on('click', '.addsection', function() { //increment sectionsCount++; //loop through each input var section = template.clone().find(':input').each(function(){ //set id to store the updated section number newId = incrementIdentifier(this.id, sectionsCount); //update for label $(this).prev().attr('for', newId); //update id this.id = newId; var baseName = this.name; var array = false; if (baseName.substr(-2) == '[]') { array = true; baseName = baseName.substr(0, baseName.length - 2); } baseName = incrementIdentifier(baseName, sectionsCount); if (array) { baseName = baseName + '[]'; } this.name = baseName; }).end() //inject new section .appendTo('#sections'); jQuery('input[name=lastSection]').val(sectionsCount); return false; }); //remove section $('#sections').on('click', '.remove', function() { //fade out section $(this).parent().fadeOut(300, function(){ //remove parent element (main section) $(this).parent().parent().empty(); return false; }); return false; });