So I have a simple page with an even simpler javaScript counter. I would like the minus and plus signs within each of these three divs to increment and decrement when you click on them. Once they have been clicked they will update the content of the span with the count class.
However, both the minus and subtraction signs are incrementing when I click on them. I implemented a for loop that would check the value to prevent this but it didnt work. The counter is also giving me negative values what can I do to fix this?
const ctaLabels = document.querySelectorAll(".cta");
Array.from(ctaLabels).forEach(function (label) {
label.addEventListener("click", function () {
const countSpan = label.parentNode.parentNode.querySelector(".count");
if (label.textContent === "+") {
countSpan.textContent = parseInt(countSpan.textContent) + 1;
} else {
countSpan.textContent = parseInt(countSpan.textContent) - 1;
}
});
});
.cta {
color: white;
background: blue;
font: var(--font-variant-6);
letter-spacing: 0.5px;
transition: all 0.15s linear;
}
.cta:hover {
background: blue;
cursor: pointer;
transition: all 0.15s linear;
}
<section id="attendees">
<div class="container">
<h3 class="title">How many people should we be expecting?</h3>
<div class="field-group --advanced">
<div class="field --counter --required">
<div class="label">Men:</div>
<div class="input">
<div>
<span class="count">0</span>
</div>
</div>
<div class="actions">
<label for="" class="cta">
<span>−</span>
</label>
<label for="" class="cta">
<span>+</span>
</label>
</div>
<label for="" class="field__label">Men:</label>
<input
required
id="men"
name="men"
type="number"
placeholder="0"
class="field__input"
/>
</div>
<div class="field --counter --required">
<div class="label">Women:</div>
<div class="input">
<div>
<span class="count">0</span>
</div>
</div>
<div class="actions">
<label for="" class="cta">
<span>−</span>
</label>
<label for="" class="cta">
<span>+</span>
</label>
</div>
<label for="" class="field__label">Women:</label>
<input
required
id="women"
name="women"
type="number"
placeholder="0"
class="field__input"
/>
</div>
<div class="field --counter --required">
<div class="label">Children:</div>
<div class="input">
<div>
<span class="count">0</span>
</div>
</div>
<div class="actions">
<label for="" class="cta">
<span>−</span>
</label>
<label for="" class="cta">
<span>+</span>
</label>
</div>
<label for="" class="field__label">Children:</label>
<input
required
id="children"
name="children"
type="number"
placeholder="0"
class="field__input"
/>
</div>
</div>
</div>
</section>
3
Answers
The problem is that you are checking
label.textContent
, but looking at the structure of your html, there is also aspan
nested under thelabel
tag. Solabel.textContent
will never be +/- and your if statment will always go on the else branch and decrement the number.You should change that if statement to check for something like this:
Or you could remove the
span
from inside thelabel
you need to trim the textContent.