John Antolin
John Antolin

Reputation: 1

How can I clone a HTML div (parent) with radio buttons (children) and change the cloned radio button's ids in JS?

I am trying to clone a div in my HTML code that contains three radio buttons, but when I clone it, the formatting is correct but the radio button IDs are identical so clicking on the original radio buttons also changes the cloned buttons.

The cloned section is created on a button click and is added to a new row at the bottom of this form (for context), but how do I change the cloned radio buttons IDs with the JS code so that the original radio buttons and cloned ones are functionally independent from one another?

function addMealOptions() {
  var original = document.getElementById("food-details");
  var clone = original.cloneNode(true);
  clone.setAttribute('id', 'cloned-food-details');

  document.getElementById("new-row").appendChild(clone);
}
<div class="food-details" id="food-details">
  <input type="radio" name="food" id="dot-1" onclick="additionalGuestCheck()">
  <input type="radio" name="food" id="dot-2" onclick="additionalGuestCheck()">
  <input type="radio" name="food" id="dot-3" onclick="additionalGuestCheck()">

  <span class="food-title">Meal choice*</span>

  <div class="category">
    <label for="dot-1">
    <span class="dot one"></span>
    <span class="food"><i class="fa-solid fa-cow"></i></span>
    </label>

    <label for="dot-2">
    <span class="dot two"></span>
    <span class="food"><i class="fa-solid fa-fish"></i></span>
    </label>

    <label for="dot-3">
    <span class="dot three"></span>
    <span class="food"><i class="fa-solid fa-carrot"></i></span>
    </label>
  </div>
</div>

Upvotes: 0

Views: 164

Answers (1)

Dmitry Shashurov
Dmitry Shashurov

Reputation: 1704

Just change name attribute for radio by adding index (2, 3, ...):

var idx = document.querySelectorAll('.food-details').length;
clone.querySelectorAll('input[type=radio]').forEach(r => {
    r.setAttribute('name', r.getAttribute('name') + idx)
});

Upvotes: 0

Related Questions