1

I'm trying to remove non-numeric characters from a string while typing, but it's not working in Chrome/Safari - anyone know a workaround?

The problem with Chrome is that if for example you enter 4 numbers, then a letter, it clears the text box and starts again, whereas other browsers just remove the letter.

Here is the code I have:

$('input[type=number]').bind('keyup', function (e) {
    this.value = this.value.replace(/[^0-9]+/g, '');
}); 

Many thanks

e-on
  • 1,547
  • 8
  • 32
  • 65

2 Answers2

3

Instead of this.value use $(this).val():

$('input[type=number]').bind('keyup', function (e) {
    $(this).val( $(this).val().replace(/[^0-9]+/g, '') );
}); 
hsz
  • 148,279
  • 62
  • 259
  • 315
  • @Christophe That's true but the problem was in the field's value setter/getter. – hsz Mar 25 '14 at 15:46
  • 1
    Can you clarify the difference between your jQuery code and OP's vanilla-js one? Which was this setter/getter problem? – Oriol Mar 25 '14 at 15:49
1

Apparently, in Chrome text in an input of type number is considered invalid, and this.value returns an empty string.

To address this, what you can do is just use a regular input of type text.

$('input').bind('keyup', function (e) {
  this.value = this.value.replace(/[^0-9]+/g, '');
}); 
Christophe
  • 27,383
  • 28
  • 97
  • 140
  • Unfortunately it's for a mobile site and need to tag the field with number so the numeric pad opens on the phone instead of the regular keyboard – e-on Mar 26 '14 at 13:16
  • @e-on then I am afraid you are out of luck. I found more information: http://stackoverflow.com/a/18853513/485406 and Chrome behaves according to the specs. – Christophe Mar 26 '14 at 16:30
  • btw if the numeric pad opens, you should not be bothered with non-numeric characters, right? – Christophe Mar 26 '14 at 16:37