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

150
Views
Javscript strip all but positive numbers and commas and dots from input

I have a type="number" input field. On keyup I need to strip all characters (including -) except for 0-9 . and , (I don't care about the order). This proves suprisingly difficult - I haven't found an answer yet.

I got the following:

$input.on('keyup change', () => {
  $input.val($input.val().replace(/[^0-9\,\.]/,''));
});

The regex is from this thread (Rails strip all except numbers commas and decimal points), but it doesn't work - if I type 1. the input vanishes.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It seems at least in some browsers (Edge) the type="number" field value returns sanitized value, which means what you see on screen might be different from what javascript sees (for example value for 99. will be 99 (no dot)).

Also these fields don't allow change cursor position, which means if you replace it's value, cursor will always be at the end.

Because of these limitation, perhaps you'd better off using regular text input and sanitize it manually leaving only characters you want:

test.addEventListener("input", e =>
{
  let start = test.selectionStart;
  //remove invalid characters
  test.value = test.value.replace(/[^0-9,.]/g, (letter, index) =>
  {
    if (index <= start)
      start--;

    return "";
  })
  //remove duplicate , and .
  .replace(/([,.])(.*)[,.]/g, (a, b, c, index) =>
  {
    if (index <= start)
      start -= a.length - b.length - c.length;

    return b+c;
  });
  test.selectionStart = test.selectionEnd = start;
});
<input id="test">

about 4 years ago · Juan Pablo Isaza Report

0

Consider using Absolute Value.

$(function() {
  $("#myNumber").on('keyup change', function(event) {
    $(this).val(Math.abs($(this).val()));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="myNumber" min="0" />

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!