Skip to content Skip to sidebar Skip to footer

How To Allow Only Numbers On A Text Input But Allow Commands With Javascript?

When searching for ways to allow only numbers on a text input you usually get something like: function keyPressEvent (e) { var keyCode = e.which || e.keyCode; if (keyCode &

Solution 1:

I actually went for an approach where I let the user type / enter whatever they want to, and manually coerce the value to be a numeric. Something like this (it's a jQuery project, but the idea can easily be re-used w/o jQuery).

fieldJq.bind('click keyup change blur focus', function (ev) {
  var curVal = $(this).val();
  $(this).val(curVal.replace(/[^0-9\.]/g, ''));
});

The idea here being that I'm letting them put whatever they want to into it (so there's no chance of breaking control commands like copy / paste, etc) but after any value change to it I remove anything that's not a digit or a decimal point. It's not 100% fireproof at this point (10.0.0 isn't invalid) but it does come close initially at least. If you didn't need floating point support and could remove the \. from the regex you'd have an enforced numeric input.

Post a Comment for "How To Allow Only Numbers On A Text Input But Allow Commands With Javascript?"