sjmartin
sjmartin

Reputation: 3962

Why does this regex wipe out all characters when a comma is entered in Firefox?

I want to use the number type input field but strip out the dollar sign if it's entered (for browsers not Chrome).

But with the code below, if I enter 300, or 300.. etc it wipes out all of my entry.

What's going on?

jQuery( 'input' ).keyup( function( ) {
  this.value = this.value.replace(/\$/g, '*');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">

Upvotes: 2

Views: 75

Answers (3)

Oriol
Oriol

Reputation: 288300

That because, when you set value, the value sanitization algorithm is invoked. For number inputs,

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

Since 300, is not a valid number, the input is cleared.

Then, instead of replacing characters, a better approach would be preventing them from being written:

jQuery('input').keydown(function(e) {
  if(e.key == '$' || e.which == 52 || e.keyCode == 52) e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">

Upvotes: 2

Pointy
Pointy

Reputation: 413757

Your code is behaving that way not because of your regular expression, but because the value of a "number" input is the empty string when it's not a valid number.

So, you type 1 ... 2 ... 3, and everything is OK. But then if you hit ,, the expression

this.value

is all of a sudden going to be the empty string. The .replace() call won't actually do anything, but you're assigning the result back to this.value so it gets rid of whatever was there.

Thus you could add a test to your code:

jQuery( 'input' ).keyup( function( ) {
  if (this.value.length)
    this.value = this.value.replace(/\$/g, '*');
});

However that's not really going to do you any good, because if a person does type a $, you'll get back the empty string and you can't fix it. You can't tell the difference from JavaScript between a "number" input that's really empty, and one that has text in it that the browser doesn't think is a nice number.

Upvotes: 2

Ivan
Ivan

Reputation: 10372

The browser doesn't let you set the input value to a invalid string. The string 100, is invalid for the input type number. Please see the W3 documentation.

Upvotes: 2

Related Questions