Reputation: 11
I've started coding roughly a month ago, so thanks for your understanding if this could've been explained better.
I am trying to have a span always display 0 when clicking a button that decreases the original amount. Instead of that happening, I am continuously getting negative numbers.
<span class="badge" id="num">40</span>
to be <span class="badge" id="num">0</span>
after clicking the button with this function
function connectionRequestCount(num) {
document.querySelector(num).innerText--
}
instead, it continues with negative numbers when clicking the button <span class="badge" id="num">-5</span>
and so on.
I've also tried getElementById & ClassName.
Any guidance would be much appreciated.
Thanks
Upvotes: 1
Views: 281
Reputation: 700
You could do something like this:
function connectionRequestCount(num) {
if(document.querySelector(num).innerText!=0){
document.querySelector(num).innerText--;
}
}
<span class="badge" id="num">40</span>
<button onclick="connectionRequestCount('#num')">Click Me!</button>
So when ever the button is clicked at 0, because of the if statement it will not go inside and not decrement the value then.
Hope that helps you
Thank You!
Upvotes: 0
Reputation: 4194
If you want to prevent the number from decreasing when it is zero, just check within the function:
function connectionRequestCount(num) {
+document.querySelector(num).innerText && document.querySelector(num).innerText--
}
This makes sure that num
's text isn't 0
before decrementing it.
Upvotes: 1