How to handle floats and decimal separators with html5 input type number

后端 未结 10 799
情话喂你
情话喂你 2020-11-27 11:15

Im building web app which is mainly for mobile browsers. Im using input fields with number type, so (most) mobile browsers invokes only number keyboard for better user exper

10条回答
  •  半阙折子戏
    2020-11-27 11:42

    I think what's missing in the answers above is the need to specify a different value for the step attribute, which has a default value of 1. If you want the input's validation algorithm to allow floating-point values, specify a step accordingly.

    For example, I wanted dollar amounts, so I specified a step like this:

     
    

    There's nothing wrong with using jQuery to retrieve the value, but you will find it useful to use the DOM API directly to get the elements's validity.valid property.

    I had a similar issue with the decimal point, but the reason I realized there was an issue was because of the styling that Twitter Bootstrap adds to a number input with an invalid value.

    Here's a fiddle demonstrating that the adding of the step attribute makes it work, and also testing whether the current value is valid:

    • jsFiddle

    TL;DR: Set the a step attribute to a floating-point value, because it defaults to 1.

    NOTE: The comma doesn't validate for me, but I suspect that if I set my OS language/region settings to somewhere that uses a comma as the decimal separator, it would work. *note in note*: that was not the case for OS language/keyboard settings *German* in Ubuntu/Gnome 14.04.

提交回复
热议问题