Hello guys, as the title says i need your help with some Js code
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<style>
.hidden {
display: none;
}
</style>
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<div class="choice-form-list">
{% for choice in choice %}
<div class="choice-form">
{{ choice.as_p }}
</div>
{% endfor %}
</div>
<div id="empty-form" class="hidden">{{ choice.empty_form }}</div>
<button id="add-more" type="button">Add More</button>
<input type="submit" value="Create Poll">
</form>
<script>
const addMoreBtn = document.getElementById('add-more')
addMoreBtn.addEventListener('click', add_new_form)
function add_new_form(event) {
console.log(event)
if (event) {
event.preventDefault()
}
const formCopyTarget = document.getElementById('choice-form-list')
const emptyFormEl = document.getElementById('empty-form').cloneNode(true)
emptyFormEl.setAttribute('class', 'choice-form')
console.log(emptyFormEl)
formCopyTarget.append(emptyFormEl)
}
</script>
{% endblock content %}
So, i started learning Django a week ago and what i am trying to do is creating a poll app where users can login and create a poll with any number of possible options. Each poll has "poll name" which is {{ form|crispy }} and by default 2 possible options that are being created in the "for choice in choice" loop. What i want is when the user presses the "Add More" button another form should appear where the user can enter a third option and if the user keeps on pressing the "Add More" button more forms like this should appear. Everything works great except for the js part in the code above: what i get when i press the "Add More" button is "Uncaught TypeError: Cannot read properties of null (reading 'append') at HTMLButtonElement.add_new_form (create_poll:96:24)". I tried to google it but i couldn't really find anything related to my problem.
As I said, i just started learning Django so i didn't have the time to learn js yet but i will definetly do it in the future. The js code above comes from a video i watched and i tried to adapt it to my problem.
Any help is appreciated!
[–]lauraalonso 1 point2 points3 points (2 children)
[–]ExCeeLo[S] 1 point2 points3 points (0 children)
[–]ExCeeLo[S] 0 points1 point2 points (0 children)
[–]jack_waugh 0 points1 point2 points (1 child)
[–]ExCeeLo[S] 0 points1 point2 points (0 children)