我目前有一个带有两个按钮的表格,分别是“添加”和“提交”。 使用javascript,只要单击“添加”,我就会向表单添加更多行。 但是,直到我单击“提交”,它才会更新表单。如何在不单击“提交”按钮的情况下添加行?
<form method="post" id="formset">
<table>
{% csrf_token %}
{{ formset.management_form }}
{{ formset }}
<div id="empty_form">
<tr>
{% for field in formset.empty_form.visible_fields %}
<td>{{ field }}</td>
{% endfor %}
</tr>
</div>
</table>
<button id="add_more" type="button">Add</button>
<button type="submit" id="submit">Submit</button>
</form>
Javascript:
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#formset').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
答案 0 :(得分:0)
查看target.oninput = functionRef;
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput
示例:
let input = document.querySelector('input');
let log = document.getElementById('log');
input.oninput = handleInput;
function handleInput(e) {
log.textContent = `The field's value is
${e.target.value.length} character(s) long.`;
}
<input type="text" placeholder="Type something here to see its length." size="50">
<p id="log"></p>