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. span class=”st0″>".addMore"".moreContainer").eq(0);
  2.   // the closest container (you can have nested containers too)
  3. ".cloneThis"// duplicate the set of form items
  4. ".set").size();
  5.   // count # of already duplicated sets
  6.  
  7.   /*
  8.    * Increment index of each for item
  9.    * we can’t use [] because of radio buttons
  10.    */"input""[""]");
  11. //    $(element).val(itemsCount); // this works as a debugger for type="text"
  12. "cloneThis");
  13.   // remove class ‘cloneThis’ to avoid duplicating it in the next round
  14.  
  15.   //    clonedSet.find("input[name*=’zoom’][value=3]").attr("checked", true); ;
  16.   // use this syntax to set a default value

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