I am managing multiple forms on a single page, and upon submission of one form, I aim to send an AJAX request with specific data to the backend view. My goal is to identify if the clicked form matches the event target in order to proceed. I attempted the following approach, but I am unsure if it is correct (the first console.log works, but the second does not):
<div id = "list">
{% for article in news %}
<a href="{{ article.resource }}"><h1>{{ article.title }}</h1></a>
<p>{{ article.published }}</p>
<img src = "{{ article.url }}">
<p>
<button><a href="#" class="vote" id="{{ article.id }}" action = "upvote">Upvote</a></button>
<button><a href="#" class="vote" id="{{ article.id }}" action = "downvote">Downvote</a></button>
</p>
<div id="span">
{% with article.upvotes.count as total_upvotes and article.downvotes.count as total_downvotes %}
<span upvote-id = "{{ article.id }}">{{ total_upvotes }}</span><span> upvote{{ total_votes|pluralize}}</span>
<span downvote-id = "{{ article.id }}">{{ total_downvotes }}</span><span> downvote{{ total_votes|pluralize}}</span>
{% endwith %}
</div>
<form method = 'post' action = '{% url "news:news_list" %}' form-id = '{{ article.id }}' class="form">
{{ form.as_p }}
{% csrf_token %}
<input type = "submit" value = "post">
</form>
{% endfor %}
</div>
{% endblock %}
{% block domready %}
const
list = document.getElementById('list'),
items = document.getElementsByClassName('vote');
forms = document.getElementsByClassName('form');
list.addEventListener('click', voteFunc);
list.addEventListener('submit', commentFunc);
function commentFunc(event){
event.preventDefault();
const clickedForm = event.target;
console.log('event triggered');
for (let form in forms){
if (form == clickedForm){
console.log('form is event.target')
$.ajax({
url: '{% url "news:news_list" %}',
type: 'POST',
data: {'id':$(event.target).attr('form-id'), 'title':$(this).elemets['title_field'].text(), 'body':$(this).elemets['body_field'].text()},
dataType: 'json'
})
}
}
}
Seeking advice on improving implementation and understanding the contents of event.target.