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