Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
How to get an HTML element to always display 0 as a number when using Javascript

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!