【发布时间】:2021-01-21 23:54:31
【问题描述】:
我有一个表单,我需要在其中添加一个允许用户添加新字段的按钮。
我正在尝试使用 JavaScript 来做这件事,但由于我不太了解这种语言,所以我迷失了一些概念。
我使用的表格是分步完成数据的,我要添加的字段如下
<div class="job-form row mb-3">
{% for form in add_trabajo %}
<div class="col-md-6">
<label for="ref" class="">Nombre</label>
{% render_field form.trabajo class="form-control" type="text" placeholder="Ej: Reparación de envolvente delantero" %}
</div>
<div class="col-md-2">
<label for="ref" class="">Descuento</label>
{% render_field form.descuento class="form-control" type="text" %}
</div>
<div class=" col-md-2">
<label for="ref" class="">Precio</label>
{% render_field form.precio class="form-control" type="text" %}
</div>
<div class="col-md-2 d-flex align-items-end">
<button id="addButton" type="button" class="btn-icon btn-icon-only btn btn-success p-2"><i class="pe-7s-plus btn-icon-wrapper"> </i></button>
</div>
{% endfor %}
</div>
我已经有按钮和一些javascript代码,但它表明以下错误
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before
which the new node is to be inserted is not a child of this node.
at HTMLButtonElement.addForm
这是我的 JavaScript 代码
let jobForm = document.querySelectorAll(".job-form")
let container = document.querySelector("#presupuestoForm")
let addButton = document.querySelector("#addButton")
let totalForms = document.querySelector("#id_trabajosarealizar_set-TOTAL_FORMS")
let formNum = jobForm.length-1 // Get the number of the last form on the page with zero-based indexing
addButton.addEventListener('click', addForm)
function addForm(e) {
e.preventDefault()
let newForm = jobForm[0].cloneNode(true) //Clone the bird form
let formRegex = RegExp(`trabajosarealizar_set-(\\d){1}-`,'g') //Regex to find all instances of the form number
formNum++ //Increment the form number
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `trabajosarealizar_set-${formNum}-`) //Update the new form to have the correct form number
container.insertBefore(newForm, addButton) //Insert the new form at the end of the list of forms
totalForms.setAttribute('value', `${formNum+1}`) //Increment the number of total forms in the management form
}
这就是我的表单结构
这就是我尝试在作业表单类和 ID 为 div-form 的分隔符之间添加新字段的地方
【问题讨论】:
标签: javascript python jquery django