0

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 }}';

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response but in your example you are inserting the html yourself. I am trying to insert it from the form object: {{ my_form.field|as_crispy_field }}
@AlbertoCarmona I haven't used crispy forms, does that render a multi-line html code?
You could try a JS multiline string: stackoverflow.com/a/805113
@AlbertoCarmona I updated my answer to show it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.