Home > Enterprise >  How to get an HTML element to always display 0 as a number when using Javascript
How to get an HTML element to always display 0 as a number when using Javascript

Time:01-27

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 id="num">40</span> to be <span 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 id="num">-5</span> and so on.

I've also tried getElementById & ClassName.

Any guidance would be much appreciated.

Thanks

CodePudding user response:

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.

CodePudding user response:

You could do something like this:

function connectionRequestCount(num) {
  if(document.querySelector(num).innerText!=0){
    document.querySelector(num).innerText--;
  }
}
<span  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!

  •  Tags:  
  • Related