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

99
Views
Quiero evitar poder elegir un número menor que cero con e.target.value

Quiero evitar que se elijan valores negativos (<0) en el campo de entrada. Siendo "0" el valor más bajo disponible para el campo de entrada.

Aquí está el código javascript y html:

 // 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 answers
Answer question

0

Su código es casi correcto.

  1. En la lógica del controlador de eventos minusButton, puede imponer que el valor nunca se establezca en un valor inferior a 0.
  2. Edite el controlador de eventos de entrada para buscar valores inferiores a 0, que no sean iguales.

Nota: el controlador de eventos que agrega a la entrada para que se active al 'cambiar' solo se ejecuta cuando el usuario realiza manualmente el cambio en el valor del cuadro de entrada, y NO cuando se cambia por código (como lo está haciendo a través de minusButton y plusButton ). Dado que el usuario hace clic en el botón (y nunca interactúa directamente con la entrada), el evento ocurre en el botón, no en el cuadro de entrada.

Puede probar el siguiente código.

 // 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; } }); });

Si estaba usando un botón de envío y el cuadro de entrada estaba en un elemento de formulario, podría haber usado el atributo min

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

Esta sería la forma ideal de front-end de hacerlo. También puede usar JavaScript, pero el usuario puede desactivarlo.

Sin embargo, debe verificar este valor (validación) cuando se envía, antes de usarlo porque incluso esto se puede omitir.

about 4 years ago · Juan Pablo Isaza Report

0

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