Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda