Create a repeated section with jQuery

The script in this post, allows you to create a repeated section where “add” link adds a new section identical to the current one below, while the “remove” link will remove the current section.

function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg){
         sectionsSelector + " " + addClass +","+
         sectionsSelector + " " + removeClass
      ).on("click", function(event){
         // Avoiding the link to do the default behavior.

         // Get the container to be removed/cloned
         var theContainer = $(this).parents(sectionsSelector);

            // Cloning the container with events
            var clonedSection = $(theContainer).clone(true);

            // And appending it just after the current container
            // If the user confirm the "Are You Sure" message 
            // we can remove the current container

               // Making fade out, hide and remove element a sequence
               // to provide a nice UX when removing element. 
                  function( ){
                        function(){ $(this).remove();  } 

This simple method can be used in a really simple way:

    '.my-repeated-section',   /* The container selector */
    '.add',                   /* The add action selector */
    '.remove',                /* The remove action selector */
    'Are you sure you want to remove this section?' /* The AYS message. */

This would be the HTML:

<div class="group-of-repeated-sections">
    <div class="my-repeated-section">
        <input type="text" value="My repeated section" />
            <a href="#" class="add"> + </a>
            <a href="#" class="remove"> - </a> 

Update: I’have prepared a live example on jsFiddle




%d blogger hanno fatto clic su Mi Piace per questo: