Using javascript, how to set a value to a number input that ends in decimal dot (ie. “100.”)

流过昼夜 提交于 2021-02-10 06:43:09

问题


Setup

Suppose I have an input like this: <input id="NumberInput" type="number" step="0.1" />

As this is a number field, it will accept digits, minus sign and decimal dot. Thus, browsers allow me to type in "100." (note the decimal dot at the end). If I leave the input, the value will still remain the same and it will allow me to return and finish the number (ie. "100.1").

Issue

I wasn't able to do this using JS in Chrome, as the following code:

document.getElementById('NumberInput').value = "100."

the input will be set to empty (regardless of the previous value) and the following error:

The specified value "100." cannot be parsed, or is out of range.`

I agree that this makes sense as "100." is by no means a valid number.

Question

Is there any way around this, so I can populate the start of a number input with JS and allow user to insert only decimal value (or edit the whole number)?

I an guessing that when typing in "100.", Chrome internally stores this value as "100" but shows the dot so that the user can continue later. This is exactly what I need, only using JS.

Notes

  • I know that defining input as type=text will solve this, but would also create some problems (which are irrelevant to this question)
  • Same error appears when using jQuery or any other JS library/framework
  • I haven't tested this on any other browser, as failing in Chrome alone is a show-stopper

Thanks in advance, cheers!


回答1:


Since you're looking to accept non-number values (like "100.") I believe usage of type="number" is too specialized for you. I recommend you use type="text" and pattern, with a custom regex:

input:invalid { background-color: #ffa0a0; }
<input type="text" pattern="[1-9][0-9]*([.][0-9]?)?"/>

The pattern I used is:

[1-9][0-9]*([.][0-9]?)?

[1-9]                     any non-0 digit (since the leading digit shouldn't be 0)
     [0-9]*               any number of followup digits
           (         )?   a whole optional section
            [.]           a single "." character
               [0-9]?     an optional single digit


来源:https://stackoverflow.com/questions/61914781/using-javascript-how-to-set-a-value-to-a-number-input-that-ends-in-decimal-dot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!