Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone radio buttons in jQuery with modified checked status?

Tags:

html

jquery

css

i have cloned radio-list,while i checked radio button and click on 'Add More' button then new cloned radio-list is added but added radio-list the radio buttons are not modified/checked by the user,the status of radio buttons are fixed. Here is my html code

<div class="Box">
   <div class="form-group">
        <label ><span>Note Type:</span></label>
         <div class="radio-list">                
                <label><input type="radio" name="optionsRadios" id="optionsRadios1" value="Subjective"> Subjective</label>
                <label><input type="radio" name="optionsRadios" id="optionsRadios2" value="Objective" > Objective</label>
         </div>
         <div class="abc">
            <button type="button" id="num">Add More</button>
         </div>
   </div>  
<div>

hers is js code.

   $("#num").click(function () {
       var p = $('.form-group').length;
       var cloned = $(".form-group:first").clone(true)
                .find('input:radio').attr('name', 'optionsRadios' + ++p).end()
                .appendTo('.Box');
    });
like image 372
HariKrishna Avatar asked Aug 20 '14 08:08

HariKrishna


1 Answers

  • your code should be wrapped with document.ready.
  • you should change name of inputs in cloned div to another unique one (to make separate group of radiobuttons).
  • you have </span> without <span>.
  • I moved <div class="abc"> out of <div class="form-group"> to prevent buttons from copying.

It should be something like in this fiddle.

var cloneId = 0;

$(document).ready(function()
{
    $("#num").click(function()
    {
        var clone = $(".form-group:first").clone(true);
        clone.find("input").prop("name", "optionsRadios" + cloneId);
        cloneId++;
        clone.appendTo(".row");
    });
});
like image 123
Regent Avatar answered Oct 18 '22 14:10

Regent