我正在开发一种用户可以添加或删除朋友信息的表单。
我当前的代码如下所示:
(() => {
let currentCount = 0;
const theForm = document.querySelector("#theForm");
document
.querySelector("#addMoreFields")
.addEventListener("click", (event) => {
event.preventDefault();
// find and clone the template content
const template = theForm.getElementsByTagName("template")[0];
const clone = template.content.cloneNode(true);
const submitButton = document.querySelector("#submitForm");
// if the submitButton is hidden, show it
if (submitButton.offsetParent === null) {
submitButton.removeAttribute("style");
}
// add class to set and name on input fields
clone.querySelector(".set").classList.add(`set-${currentCount}`);
clone
.querySelector(".first_name")
.setAttribute("name", `firstName[${currentCount}]`);
clone
.querySelector(".middle_name")
.setAttribute("name", `middleName[${currentCount}]`);
clone
.querySelector(".last_name")
.setAttribute("name", `lastName[${currentCount}]`);
clone.querySelectorAll(".checkbox").forEach(function (item) {
item.setAttribute("name", `checkbox[${currentCount}]`);
});
clone.querySelectorAll(".radio").forEach(function (item) {
item.setAttribute("name", `radio[${currentCount}]`);
});
// remove button
clone
.querySelector(".removeSet")
.setAttribute("id", `remove-${currentCount}`);
clone
.querySelector(".removeSet")
.setAttribute("data-number", currentCount);
theForm.append(clone);
// add event listener to removeSet button
document
.querySelector(`#remove-${currentCount}`)
.addEventListener("click", (event) => {
event.preventDefault();
const setName = `.set-${event.target.getAttribute("data-number")}`;
document.querySelector(setName).remove();
});
currentCount++;
});
UYOU
相关分类