0

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.

Tonald Drump
  • 1,227
  • 1
  • 19
  • 32
  • You should add the ``g`` flag to replace all matches, not just the first one. Also, you don't need to escape ``,``: ``/[^0-9,\.]/g``. – Cubix48 Mar 12 '22 at 21:37
  • Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Mar 13 '22 at 00:30

2 Answers2

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">
vanowm
  • 9,466
  • 2
  • 21
  • 37
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" />
Twisty
  • 30,304
  • 2
  • 26
  • 45