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

98
Visualizações
I want to prevent being able to choose a number less than zero with e.target.value

I want to prevent negative values ( < 0) to be chosen on input field. Being "0" the lowest value available for the input field.

Here is the javascript and html code:

// Button functions
const minusButton = document.getElementById('minus');
const plusButton = document.getElementById('plus');
const inputField = document.getElementById('amount');

minusButton.addEventListener('click', event => {
    event.preventDefault();
    const currentValue = Number(inputField.value) || 0;
    inputField.value = currentValue - 0.01;
});

plusButton.addEventListener('click', event => {
    event.preventDefault();
    const currentValue = Number(inputField.value) || 0;
    inputField.value = currentValue + 0.01;
});

// Returning 0 when clearing input
const numInputs = document.querySelectorAll('input[type=number]')

numInputs.forEach(function(input) {
    input.addEventListener('change', function(e) {
        if (e.target.value == '') {
            e.target.value = 0
        }
    })
})
<button class="input-btn" id="minus">−</button>
<button class="input-btn" id="plus">+</button>
<input class="input" type="number" value="0" id="amount"/>

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

0

Your code is almost correct.

  1. In the minusButton event handler logic, you can enforce that the value never gets set to anything lower than 0.
  2. Edit the input event handler to check for values lower than 0, not equal to it.

Note: the event handler you add to input to fire upon 'change' only gets executed when the user manually makes the change to the value of input box, and NOT when it gets changed by code (as you're doing through minusButton and plusButton). Since, the user clicks the button (and never interact with the input directly), the event happens on the button, not the input box.

You can give below code a try.

// Button functions
const minusButton = document.getElementById("minus");
const plusButton = document.getElementById("plus");
const inputField = document.getElementById("amount");

minusButton.addEventListener("click", (event) => {
  event.preventDefault();
  const currentValue = Number(inputField.value) || 0;
  // if less than 0, set to 0, else currentValue - 0.01
  inputField.value = currentValue - 0.01 < 0 ? 0 : currentValue - 0.01;
});

plusButton.addEventListener("click", (event) => {
  event.preventDefault();
  const currentValue = Number(inputField.value) || 0;
  inputField.value = currentValue + 0.01;
});

// Returning 0 when clearing input
const numInputs = document.querySelectorAll('input[type="number"]');

numInputs.forEach((input) => {
  input.addEventListener("change", function (e) {
    if (e.target.value === "" || e.target.value < 0) {
      e.target.value = 0;
    }
  });
});

If you were using a submit button and the input box was in a form element, you could have used the min attribute

<input class="input" type="number" value="0" id="amount" min="0" />

This would be the ideal front-end way of doing it. You could use JavaScript too, but it can be disabled by the user.

You should, however, check this value (validation) when it gets submitted, before you use it because even this can be bypassed.

about 4 years ago · Juan Pablo Isaza Relatório

0

let newValue = currentValue - 0.01
if(newValue < 0) {
  newValue = 0
}
inputField.value = newValue
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