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

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

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 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