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

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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