Reputation: 477
I'd like to add a form field to the template when the user clicks on a button via javascript. I don't want to hide it and just make it appear, I need to insert it because it can be loaded into multiple parts. This is what I've tried but no luck.
document.getElementById("div_id").value = '{{ my_form.field|as_crispy_field }}';
Upvotes: 0
Views: 407
Reputation: 1810
Here is an example:
// update element innerHTML with input field
function addField2(e) {
e.preventDefault();
var container = document.getElementById("field_2_container");
var input = `
<div class="some_class">
<input type="text" name="field_2" id="id_field_2">
</div>
`;
// append input field to the element
container.innerHTML += input;
}
<form id="form">
<div id="field_1_container">
<input type="text" name="field_1" id="id_field_1">
</div>
<div id="field_2_container"></div>
<div id="field_3_container"></div>
<button onclick="addField2(event)">Add field 2</button>
</form>
Upvotes: 1