Gaurav Aggarwal Gaurav Aggarwal - 5 months ago 9
HTML Question

Adding div dynamically but issues with input type radio

I am using a

<a>
on click of which i am cloning a div. In div i have two radio buttons with same name.

Now the problem is when i select one radio option and clone the div the next two radio buttons come with same name and selected radio button from last div got unselected.



$('.addMore').on('click', function() {
$('.addMoreDiv:last').clone().insertAfter('.addMoreDiv:last');
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="addMoreDiv">
<label>
<input type="radio" name="optradio">Radio 1
</label>
<label>
<input type="radio" name="optradio">Radio 2
</label>
</div>

<a href="#" class="addMore">Add More</a>





I tried updating name according to length but didn't work and name updates after addition of div.

Is there any option so that when i add new div it comes with different names also the selection of last div will not effect?

Answer

As suggested by @sailens; we need to change the name of radio group so that it will be considered as totally newer set of radio buttons. We can achieve it in following way:

var count = 0;
$('.addMore').on('click', function() {
  var clonedDiv = $('.addMoreDiv:last').clone();
  clonedDiv.find("input[type=radio]").each(function(){
    $(this).attr("name","optradio_"+count);
  });
  count++;
  clonedDiv.insertAfter('.addMoreDiv:last');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="addMoreDiv">
  <label>
    <input type="radio" name="optradio">Radio 1
  </label>
  <label>
    <input type="radio" name="optradio">Radio 2
  </label>
</div>

<a href="#" class="addMore">Add More</a>

Comments