56 lines
2.1 KiB
JavaScript
56 lines
2.1 KiB
JavaScript
|
document.addEventListener("DOMContentLoaded", (event) => {
|
||
|
const totalForms = document.getElementById("id_items-TOTAL_FORMS")
|
||
|
const initialForms = document.getElementById("id_items-INITIAL_FORMS")
|
||
|
const minForms = document.getElementById("id_items-MIN_NUM_FORMS")
|
||
|
const maxForms = document.getElementById("id_items-MAX_NUM_FORMS")
|
||
|
const formsetContainer = document.getElementById("formset-container")
|
||
|
|
||
|
console.log(totalForms.value, initialForms.value, minForms.value, maxForms.value, formsetContainer)
|
||
|
|
||
|
const renumberAll = () => {
|
||
|
let id = 0;
|
||
|
formsetContainer.querySelectorAll("tr").forEach(row => {
|
||
|
row.querySelectorAll("[name^='items-'], [id^='id_items-']").forEach(element => {
|
||
|
const namePattern = /items-(\d+)-/;
|
||
|
const idPattern = /id_items-(\d+)-/;
|
||
|
element.name = element.name.replace(namePattern, `items-${id}-`);
|
||
|
element.id = element.id.replace(idPattern, `id_items-${id}-`);
|
||
|
});
|
||
|
id += 1;
|
||
|
});
|
||
|
totalForms.value = id; // Update the total form count
|
||
|
};
|
||
|
|
||
|
const clearValues = (node) => {
|
||
|
node.querySelectorAll("input").forEach(element => {
|
||
|
if (element.type === "checkbox" || element.type === "radio") {
|
||
|
element.checked = false;
|
||
|
} else {
|
||
|
element.value = "";
|
||
|
}
|
||
|
})
|
||
|
}
|
||
|
|
||
|
document.getElementById("add-formset-item").addEventListener("click", () => {
|
||
|
if (parseInt(totalForms.value) >= parseInt(maxForms.value)) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
const template = formsetContainer.firstElementChild;
|
||
|
const newForm = template.cloneNode(true)
|
||
|
formsetContainer.appendChild(newForm)
|
||
|
clearValues(newForm)
|
||
|
|
||
|
renumberAll();
|
||
|
});
|
||
|
|
||
|
formsetContainer.addEventListener("click", (event) => {
|
||
|
if (event.target.classList.contains("remove-formset-item") && (parseInt(totalForms.value) > parseInt(minForms.value))) {
|
||
|
const clickedButton = event.target
|
||
|
clickedButton.closest("tr").remove()
|
||
|
renumberAll();
|
||
|
}
|
||
|
});
|
||
|
|
||
|
})
|