Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
I want to include the negative sign for input by a function

hi i have this function to allow digits 0-9 but i want to include the negative sign. how would i do that? Thanks.

function allowNumbersOnly(e) {
      var code = (e.which) ? e.which : e.keyCode;
      if (code > 31 &&(code < 48 || code > 57)) {
          e.preventDefault();}
      else if (code==109){
      e.preventDefault();
      }
    }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Also see HTML text input allow only numeric input.

Add a test to check if it's the first character and allow "-". Otherwise, run the other tests. e.g.

function allowNumbersOnly(e) {
  let len = e.target.value.length;
  var code = (e.which) ? e.which : e.keyCode;
  if (len == 0 && code == 45)  {
    return;
  }
  if (code > 31 && (code < 48 || code > 57)) {
    e.preventDefault();
  } else if (code == 109) {
    e.preventDefault();
  }  
}

window.onload = function() {
  document.querySelector('#i0').addEventListener('keypress', allowNumbersOnly, false);
}
<input id="i0">

However, that only allows entry of "-" as the first and only character, it can't be added later to change say "1" to "-1".

Personally, I find this kind of UI feature very annoying, e.g. it prevents keystrokes to copy and paste values. Just let the user enter whatever they like and deal with it. If it doesn't fit the required criteria, just let the user know with a friendly message and let them fix it.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda