So currently i have a card which has some radio buttons with the name="radio-0" i want when i clone the card that all the radio buttons to change to name="radio-1" for exapmle
I have made a function that get the last child from the element being but it isn't working and only works one time.
My fiddle https://jsfiddle.net/abdotamer3/s57jauxw/22/
My function:
function nameRadioButtons(clone, radioButtons) {
var allQuestions = clone.querySelector(".radioItemToggle:last-child");
var radioID = allQuestions.getAttribute("name").split("-")[1];
console.log(radioID)
radioButtons.forEach((element, index) => {
radioID = 1
element.setAttribute("name", "radio-" radioID.toString());
});
}
My cloning function:
function cloneQuestion() {
var question = document.querySelector(".questions");
var clone = $(question).clone(true, true).get(0);
var numItems = $(".questions").closest(".radioListItemPrimaryContent").length;
var radioButtons = question.querySelectorAll(".radioItemToggle");
console.log(numItems);
nameRadioButtons(clone, radioButtons);
clone.querySelector(".questionMainTextArea").value = "Untitled Question";
var addBtn = document.querySelector(".addQuestionBtnRow");
var tbody = addBtn.parentNode;
tbody.insertBefore(clone, addBtn);
}
CodePudding user response:
Create a global variable to store the currently maximum question index, and add 1 to it every time before setting the new name.
let radioGroupIndex = 0
function nameRadioButtons(clone) {
radioGroupIndex
clone.querySelectorAll('input[type=radio]').forEach(_radio => {
_radio.setAttribute('name', `radio-${radioGroupIndex}`)
})
}