jQuery( document ).ready( function() { // Enable the delete buttons enableDelete(); // When the #addFormField button is clicked jQuery( '#addFormField' ).click( function() { // Get the ID of the last field that currently exists var lastFieldID = jQuery( '#formFields' ).children( 'div.form-field:last' ).attr( 'id' ); // Strip out the formField_ part of the ID to return just the number lastFieldID = lastFieldID.replace( /formField\_/, '' ); // Add 1 to the last ID number var newID = parseInt( lastFieldID ) + 1; // Clone the div.form-field template, append it to the #formFields div and fade it in jQuery( '#newFormField > div.form-field' ).clone( true ).attr( 'id', 'formField_' + newID ).appendTo( '#formFields' ).fadeIn( 500, function() { enableDelete(); } ); // Assign the new fields jQuery object to the newfield var var newfield = jQuery( '#formField_' + newID ); // Get the html contents of our new field in to the newhtml var var newhtml = newfield.html(); // Replace any _x's with our new ID (e.g. _2 ) newfield.html( newhtml.replace( /\_x/g, '_' + newID ) ); // Set the default display order of this field jQuery( '#iwacf_displayorder_' + newID ).val( newID+1 ); // Enable the delete button for this field enableDelete(); } ); } ); function enableDelete() { // When a delete button is clicked jQuery( '.deleteFieldButton' ).click( function() { // Get the ID of this delete button var deleteID = jQuery( this ).attr( 'id' ) // Get the ID number of the form field this remove button belongs to var fieldSequence = deleteID.replace( /removeField\_/, '' ); // Find this form field, fade it out and when thats finished, remove it from the page jQuery( '#formFields > #formField_' + fieldSequence ).fadeOut( 500, function() { jQuery( this ).remove(); } ); } ); }