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

244
Views
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 answers
Answer question

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