4

How do I get the value of an <input> tag with the type number? This sounds like a ridiculous question, but in a recent1 Chrome update, the following code doesn't work if an invalid character is entered into the field:

element.value     //does not work as expected, will return ""

enter image description here
Demo: http://jsfiddle.net/DerekL/zT4bf/

Now this is frustrating. I am using this piece of code to forbidden invalid characters:

$("element").on("input", function(){
    this.value = this.value.replace(/[^0-9]/g, "");
});

But since it returns "" now if an invalid character is entered, the whole field would be emptied. This behavior did not happen before, just in the recent Chrome update. This works fine in Firefox (although I do not need this to work in Firefox.)

Is there a way to get the exact value of the <input>? Thanks.

1: 36.0.1985.49 beta-m

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • See [How to get the raw value an field?](http://stackoverflow.com/questions/18852244/how-to-get-the-raw-value-an-input-type-number-field) - short answer, don't use `type=number` :( – akxlr Jun 07 '14 at 04:04
  • @akxlr - Hm, that's interesting. I can get the value of the field in Chrome 35, but not in Chrome 36. Anyway, that link didn't answer the question. It only explained why. – Derek 朕會功夫 Jun 07 '14 at 04:07
  • *exact value of the ``* with numbers ONLY or you want the `+` sign as well – Mr. Alien Jun 07 '14 at 04:18
  • @Mr.Alien - What I trying to get is the exact string the user has entered. – Derek 朕會功夫 Jun 07 '14 at 04:20
  • If you really, really wanted to make it look like a number input you could probably fake it by using a normal input without the right border, and a number input only showing the arrows directly next to it, attach scroll listeners to the normal text input, attach onchange listeners to the number input, make sure tabbing through the form inputs would skip the 2nd input..... – JustcallmeDrago Jun 07 '14 at 04:29

1 Answers1

-1

What I trying to get is the exact string the user has entered.

So the best thing to user over here is input[type=text] because when you will use type number, it will obviously cause issue.

As far as increment functionality goes, I don't think its technically applicable to your issue, because even if the user types 1+ and he tries to increment, the + will be removed by the number field automatically. Also it won't make any sense adding any other characters apart from numbers in the number field.

If you want to validate the characters submitted, use pattern attribute where you can customize the validation pattern.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278