Search code examples
javascriptgoogle-chromeinputchromium

Chrome/Chromium input number value empty when last char is dot


In Chrome (or other Chromium browser) when I try to get a value of a number input field the value is empty when the last char is a dot (.).

Here is the simplest example I could think of:

<input type="number" oninput="console.log(event.target.value)">

In Chrome when typing for example "123.45" will result in this output:

1
12
123

123.4
123.45

In Firefox I get something more like I would expect:

1
12
123
123    
123.4
123.45

Getting valueAsNumber instead of value will result in a NaN if the last char is dot, so no success there either. Is there a way to get what is is the actual value of the field (or at least the value without the dot) and not something that is already parsed somehow?

UPDATE:

Thanks to @Kaiido I'm a little closer as to why this happens In my Chrome browser navigator.languages is set to ['en-US', 'en', 'nl'] in Firefox it's set to just ['en-US', 'en']

This explains the difference between the 2 browsers (in my case) and why in Chrome I can use , as well as ..

But I still need a solution for the problem. The most important thing in my case is that I need a distinction between the field being empty or some other value that somehow can't de parsed to a number. So now the question is more is there a way to get the value of what's actually being types in the field.


Solution

  • Use the 'step' attribute to make it validate and use the locales delimiter.

    <input type="number" step="0.01" oninput="console.log(event.target.value)" />
    

    More information:

    <input type="number" oninput="console.log('VAL: %s|%s|%s', this.value, this.checkValidity(), this.validationMessage)" step="0.1">
    

    Entering a delimiter not used in the current locale the validity and corresponding message will indicate 'this is not a number', once more digits are entered - up to the limit of precision the step attribute allows - it will parse to valid values again. Your GUI should correspondingly indicate the current validity - if your code requires it to always be usable as a valid number you could save the last value that passed validation, depending on your use case.

    Also consider the use of the character "e" which may be cause for a temporary invalid value!