1

the task looks simple. I have to remove non-numeric characters from an input field of type "number" on keyup in firefox.

The code:

$("#field").on("keyup", function() {
 regex = /[\\D]+/;
 $(this).val( $(this).val().replace(regex, '') );
});

Unfortunately as soon as a non-numeric character enters the field, its whole content gets replaced by the empty string.

For example:

234d = emptied > should be 234

Solution (here because the question has been closed):

This example works. I found out that it has to do with the field type. If the input in the field of type "number" contains non numeric characters, firefox shows the input but doesn't store it in the input object. As soon as I use a text input everything works fine. Seems to be a Firefox issue.

I think this question is NOT duplicate because it seems to regard a Firefox issue with input fields of type "number".

Bernhard Kraus
  • 329
  • 1
  • 3
  • 21
  • 1
    `regex = /\D+/;` ..... `/[\\D]+/` matches combination of `\s` and `Ds` – Pranav C Balan Aug 04 '16 at 08:39
  • `var regex = /\D+/g` to remove all non-numeric characters. `$(this).val(function(i, val) { return val.replace(/\D+/g, ''); });` – Tushar Aug 04 '16 at 08:40
  • `/[\\D]+/;` matches ``\``s and `D`s. If you use a constructor notation, `new RegExp("[\\D]+", "g")` would work, but in a regex literal, you only need one ``\`` with a shorthand character class/special characters. – Wiktor Stribiżew Aug 04 '16 at 08:40
  • Ok, thx. I've also tried /^[^0-9]+/g and /[^0-9]/g. Have tried new RegExp() as well but the field always gets emptied. Weird but for sure my fault somewhere. – Bernhard Kraus Aug 04 '16 at 08:48

2 Answers2

2

var val = '234d'.replace(/[^0-9]/g, '');

console.log(val);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
1
var myString = '234d';

Try this line:

myString = myString.replace(/\D/g,'');

Reference: strip non-numeric characters from string

Community
  • 1
  • 1
Abbi Cse
  • 11
  • 1
  • This example works. I found out that it has to do with the field type. If the input in the field of type "number" contains non numeric characters, firefox shows the input but doesn't store it in the input object. As soon as I use a text input everything works fine. So I suppose it is a firefox issue. – Bernhard Kraus Aug 04 '16 at 08:58