javascript - How to automatically add a new name to cloned radio buttons in a new card
问题描述
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);
}
解决方案
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}`)
})
}
推荐阅读
- java - Can I perform validation for a specific integer size using Hibernate?
- postgresql - 如何在 Postgresql 中删除所有以前缀开头的数据库
- javascript - 如何在不刷新/提交页面的情况下发送 POST 方法
- ios - 使用 urlsessiondownloadtask 从 url 下载文件后,文件未打开
- java - 无法从 HDFS 复制到 S3A
- javascript - 如何在页面上水平居中固定宽度的表格?带有自动表格的jsPDF
- python - 平均(似然)编码
- python - python中的矩阵COUNT + GROUP BY
- php - 如何调试以 137 错误退出的 php 脚本?
- azure - .Net Core 2.2 指定的 Azure 回复 url 与为应用程序配置的回复 url 不匹配