Duplicating sets of radio buttons with jQuery

We all love the “add more” links for adding more form items to forms. More pictures to upload, more categories to add. You just name them with empty square brackets and then clone them.

  1.  
  2. <input type="file" name="file[]" value="">
  3. <a href="" id="addMoreUploads">add more</a>
  4.  

But what if you need to clone sets of radio buttons? You end up with a single group of radio buttons – not with a group of radio button groups.

  1.  
  2. <div class="moreContainer">
  3. <div class="cloneThis set">
  4. <input type="radio" name="options[]" value="1"> one
  5. <input type="radio" name="options[]" value="2"> two
  6. <input type="radio" name="options[]" value="3"> three
  7. </div>
  8. <a href="" class="addMore">add more</a>
  9. </div>
  10.  

If you clone the whole cloneThis group you’ll get a group of six radio buttons but you’ll be able to choose just one.

Unfortunately, you have to give up the empty square brackets and start numbering them (name=”options[0]”). In the cloning function then you replace the cloned number with an ever increasing counter value.

  1.  
  2. $(document).ready(function() {
  3.  
  4. $(".addMore").click(function() {
  5.   var parentContainer = $(this).parents(".moreContainer").eq(0);
  6.   // the closest container (you can have nested containers too)
  7.   var cloneSource = parentContainer.find(".cloneThis");
  8.  
  9.   var clonedSet = cloneSource.clone();
  10.   // duplicate the set of form items
  11.   var itemsCount = parentContainer.find(".set").size();
  12.   // count # of already duplicated sets
  13.  
  14.   /*
  15.    * Increment index of each for item
  16.    * we can’t use [] because of radio buttons
  17.    */
  18.   clonedSet.find("input").each(function(index, element) {
  19.     this.name = this.name.replace(/\[0\]/, "["+itemsCount+"]");
  20. //    $(element).val(itemsCount); // this works as a debugger for type="text"
  21.   });
  22.  
  23.   clonedSet.removeClass("cloneThis");
  24.   // remove class ‘cloneThis’ to avoid duplicating it in the next round
  25.  
  26.   //    clonedSet.find("input[name*=’zoom’][value=3]").attr("checked", true); ;
  27.   // use this syntax to set a default value
  28.  
  29.   cloneSource.after(clonedSet);
  30.  
  31.   return false;
  32. });
  33.  
  34. });
  35.  

This function is generic and works for any set of input fields (not textarea and select though). You can have many “add this” and “add that” on a single page and still use the same function. You just have to switch from using id to class for identifying the containers, links and cloning sources.

Leave a Reply