html5 input for money/currency

前端 未结 7 1513
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 01:55

I seem unable to work out what to use for accepting monetary values on a form.

I have tried...



        
7条回答
  •  轮回少年
    2020-12-08 02:06

    Enabling Fractions/Cents/Decimals for Number Input

    In order to allow fractions (cents) on an HTML5 number input, you need to specify the "step" attribute to = "any":

    
    

    This will specifically keep Chrome from displaying an error when a decimal/fractional currency is entered into the input. Mozilla, IE, etc... don't error out if you forget to specify step="any". W3C spec states that step="any" should, indeed, be needed to allow for decimals. So, you should definitely use it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step

    Note that if you want the up/down buttons to do a specific granularity, then you must specify a numeric step such as ".01".

    Also, the number input is now pretty widely supported (>90% of users).


    What Input Options are there for Money/Currency?

    The title of the question has since changed and takes on a slightly different meaning. One could use both number or text input in order to accept money/decimals.

    For an input field for currency/money, it is recommended to use input type of number and specify appropriate attributes as outlined above. As of 2020, there is not a W3C spec for an actual input type of currency or money.

    Main reason being it automatically coerces the users into entering a valid standard currency format and disallows any alphanumeric text. With that said, you could certainly use the regular text input and do some post processing to only grab the numeric/decimal value (there should be server side validation on this at some point as well).

    The OP detailed a requirement of currency symbols and commas. If you want fancier logic/formatting like that, (as of 2020) you'll need to create custom JS logic for a text input or find a plugin.

提交回复
热议问题