I am very new to front end development and recently started setting EventListeners for my HTML elements with JS opposed to adding an onclick html tag as I was told onclick is bad practice (is that true?)
In the below code, the phrase that I log in the console ("Test, the input tag was clicked") always logs twice every time an input is clicked. TThe event should of course only fire once and I have no idea it prints in the console twice, what am I doing wrong?
(function () {
window.addEventListener("load", () => {
const documentParentElement = document.querySelectorAll(".rating-button");
documentParentElement.forEach(element => {
element.addEventListener("click", event => {
const targetElement = event.target;
console.log("Test, the input tag was clicked")
const selectedRating = targetElement.value;
})
});
});
}());
<div class="rating" data-decision-id="{{decision.id}}" data-user-id="{{decision.user_id}}">
<input type="radio" class="rating-button" id="star-1-{{decision.id}}" name="rating" {% if decision.rating.rating == 1 %} checked {% endif %} value="1"/>
<input type="radio" class="rating-button" id="star-2-{{decision.id}}" name="rating" {% if decision.rating.rating == 2 %} checked {% endif %} value="2"/>
<input type="radio" class="rating-button" id="star-3-{{decision.id}}" name="rating" {% if decision.rating.rating == 3 %} checked {% endif %} value="3"/>
<input type="radio" class="rating-button" id="star-4-{{decision.id}}" name="rating" {% if decision.rating.rating == 4 %} checked {% endif %} value="4"/>
<input type="radio" class="rating-button" id="star-5-{{decision.id}}" name="rating" {% if decision.rating.rating == 5 %} checked {% endif %} value="5"/>
</div>