I created this form, which allows you to create multiple instances of the "thing" ... Basically, the necessary fields for the "thing" are enclosed within the section. When the user clicks the add more button, I use the Jquery clone to copy the last element of the section in the series and paste it before the add more button. I clear any fields in a new section using jQuery.
The thing on this form that I created is that you can fill in the information in the fields of any section, but then when you decide that you do not want any particular section to be larger, you can simply delete it. Then I have a script that will go through the remaining sections, re-reading all the attributes and elements of the element so that everything is numbered accordingly (it is easier to process the form with PHP after submitting), and the remaining information, ve will be saved - even after re-numbering elements and attributes.
Here's the handle: http://codepen.io/JonnyNineToes/pen/AgEax
Mandatory code:
// when the user clicks the "add more" button... $('.add_btn').click(function(){ // clone the previous element (a "repeatable" element), and insert it before the "add more" button $(this).prev('.repeatable').clone().insertBefore(this).html(); // get the number of repeatable elements on the page var num = $('.repeatable').length; // again, get the previous element (a "repeatable" element), and change the header to reflect it new index $(this).prev('.repeatable').children('h2').html('Person ' + num); // now, go through all text boxes within the last "repeatable" element... $('.repeatable').last().find('input').each(function(){ // ...change their "structure" data attributes to reflect the index+1 value of the "repeatable" element dattr = $(this).data('structure') + num; $(this).attr({ 'id':dattr, 'name':dattr // update the "for" attribute on the parent element (label) }).parent('label').attr('for',dattr); // clear the input field contents of the new "repeatable" // if the type of the input is "radio"... if ($(this).attr('type') == 'radio') { // remove the checked attribute /*$(this).removeAttr('checked');*/ // for all other inputs... } else { // clear the value... $(this).val(''); } }); // run the "destroy" method... I forget why... just do it, and don't gimme no lip. destroy(); updateRemoveLinks(); });
I have a problem with the switches. If I clicked one of the radio buttons in the last section, and then click โadd moreโ to add another section after it, the radio buttons are blank (none are selected) in the section that is being cloned, and instead copied to a new section, Try the pen ... click on one of the radio buttons in the section, and then click "add more." You will see what I mean.
I canโt understand what I did wrong because it is so ... Or if I forgot something or looked at each other?
source share