Hi I created a web app with Django. In this app there are 6 cards with a button for increase and a button for decrease the quantity of food to buy. I have a problem: only the buttons in the first card work. Here's the HTML code
<div >
<div >
{% for roll in rolls %}
<div >
<div style="width: 16rem;">
<img src="{{ roll.immagine.url }}" alt="...">
<div >
<h5 >{{ roll.nome }} Roll</h5>
<p >€ {{ roll.prezzo }}</p>
<button id="incrementBtn" style="border-radius: 8px; background-color:orange;"> </button>
<span id="counter">0</span>
<button id="decrementBtn" style="border-radius: 8px; background-color: lightsalmon;">-</button>
<a href="{% url 'ordina' %}" >Acquista</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
Here's the Javascript code:
document.addEventListener("DOMContentLoaded", function() {
let idCounter = "counter1, counter2, counter3, counter4, counter5, counter6";
let arrIdCounter = idCounter.split(", ");
console.log(arrIdCounter);
let valueCounter = document.getElementById('counter').innerHTML;
const incrementBtn = document.getElementById('incrementBtn');
const decrementBtn = document.getElementById('decrementBtn');
incrementBtn.addEventListener('click', () => {
console.log(valueCounter);
valueCounter ;
document.getElementById('counter').innerHTML = valueCounter;
console.log(valueCounter);
});
decrementBtn.addEventListener('click', () => {
if (valueCounter > 0)
{
valueCounter--;
}
document.getElementById('counter').innerHTML = valueCounter;
});
});
CodePudding user response:
When you render your file you will have something like:
<div >
<div style="width: 16rem;">
...
<button id="incrementBtn" ...> </button>
...
<button id="decrementBtn" ...>-</button>
...
</div>
</div>
<div >
<div style="width: 16rem;">
...
<button id="incrementBtn" ...> </button>
...
<button id="decrementBtn" ...>-</button>
...
</div>
</div>
<div >
<div style="width: 16rem;">
...
<button id="incrementBtn" ...> </button>
...
<button id="decrementBtn" ...>-</button>
...
</div>
</div>
How your script may know which element take? You cannot have more than 1 html element with same id, they have to be unique. To do so, you may change you buttons' ids to:
<button id="incrementBtn_{{ poll.id }}" style="border-radius: 8px; background-color:orange;"> </button>
And your variable to array:
const incrementBtn = document.querySelectorAll('[id^="incrementBtn"]');
But then of course you have to use it in loop.