1

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 < 48 || keyCode > 57) {
        return false;
    }
}

But the problem is that this makes keys that only do commands not work. Starting with backspace and delete, but even ctrl+a or f5. I know I can create exceptions for all of this, but I think this will be a waste of time. Is there some easy way to do what I want? Is there something like detecting the character that will be added to the text, and not the key pressed?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Cokegod
  • 8,256
  • 10
  • 29
  • 47
  • you could do what they suggested here: http://stackoverflow.com/questions/950208/textbox-with-alphanumeric-check-in-javascript for alpha characters. – scrappedcola Sep 20 '11 at 16:38

1 Answers1

2

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.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • I guess this is the best answer at this point and that meanwhile I should just wait for the number input type to be implemented in most browsers. Thank anyway! – Cokegod Sep 21 '11 at 10:15
  • In IE7 it always puts cursor to the end, can be fixed by checking before replace: if (curVal.search(/[^0-9\.]/g)>-1) – samir105 Jan 27 '12 at 13:02