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

103
Visualizações
Html textbox that prevents user from entering negative numbers rounds up positive decimal numbers

I have this code that prevents the user from entering negative weights in the Weight textbox.

<input type="number" min="0" 
oninput="this.value = !!this.value && Math.abs(this.value)>= 0 ? Math.abs(this.value) : null">

Scenario 1 is working fine: Input: 1.23 Output 1.23

Scenario 2: Input: 0.05 Output 5 (I would like to get 0.05)

When I enter decimal numbers like 0.04 or 0.05, I am getting 4 or 5. I would like to get the decimal numbers as it is.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Just use a regular expression to strip all non-numberic digits.

  • Not allow period(.) = string.replace(/[^0-9]/g, '')
  • Allow period(.) for decimals = string.replace(/[^\d.-]/g, '')

<div class="box-tricks">
 <input type="number" min="0" oninput="this.value = this.value.replace(/[^0-9]/g, '')"> 
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You are probably better off with using onblur instead of oninput as this will give the user the opportunity to complete his input before it gets "mutilated" by the event handler. I also changed the input type to "text" as this will require the decimal dot "." to be entered - independently from any locale setting that might apply to your (or you users') browsers.

<input type="text"
onblur="this.value = !!(+this.value) && Math.abs(+this.value)>= 0 ? Math.abs(+this.value).toFixed(2) : null;console.log(this.value)">

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