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

4
  • 1
    regex = /\D+/; ..... /[\\D]+/ matches combination of \s and Ds Commented Aug 4, 2016 at 8:39
  • var regex = /\D+/g to remove all non-numeric characters. $(this).val(function(i, val) { return val.replace(/\D+/g, ''); }); Commented Aug 4, 2016 at 8:40
  • /[\\D]+/; matches \s and Ds. 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. Commented Aug 4, 2016 at 8: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. Commented Aug 4, 2016 at 8:48

2 Answers 2

2

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

console.log(val);

Sign up to request clarification or add additional context in comments.

Comments

1
var myString = '234d';

Try this line:

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

Reference: strip non-numeric characters from string

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.