Is there a float input type in HTML5?

前端 未结 9 1799
失恋的感觉
失恋的感觉 2020-11-22 11:32

According to html5.org, the \"number\" input type\'s \"value attribute, if specified and not empty, must have a value that is a valid floating point number.\"

Yet it

相关标签:
9条回答
  • 2020-11-22 12:30
    <input type="number" step="any">
    

    This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.

    0 讨论(0)
  • 2020-11-22 12:32

    Based on this answer

    <input type="text" id="sno" placeholder="Only float with dot !"   
       onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||  
       event.charCode == 46 || event.charCode == 0 ">
    

    Meaning :

    Char code :

    • 48-57 equal to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    • 0 is Backspace(otherwise need refresh page on Firefox)
    • 46 is dot

    && is AND , || is OR operator.

    if you try float with comma :

    <input type="text" id="sno" placeholder="Only float with comma !"   
         onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||  
         event.charCode == 44 || event.charCode == 0 ">
    

    Supported Chromium and Firefox (Linux X64)(other browsers I does not exist.)

    0 讨论(0)
  • 2020-11-22 12:33

    I have started using inputmode="decimal" which works flawlessly with smartphones:

    <input type="text" inputmode="decimal" value="1.5">

    Note that we have to use type="text" instead of number. However, on desktop it still allows letters as values.

    For desktop you could use:

    <input type="number" inputmode="decimal">

    which allows 0-9 and . as input and only numbers.

    Note that some countries use , as decimal dividor which is activated as default on the NumPad. Thus entering a float number by Numpad would not work as the input field expects a . (in Chrome). That's why you should use type="text" if you have international users on your website.


    You can try this on desktop (also with Numpad) and your phone:

    <p>Input with type text:</p>
    <input type="text" inputmode="decimal" value="1.5">
    <br>
    <p>Input with type number:</p>
    <input type="number" inputmode="decimal" value="1.5">


    Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode

    0 讨论(0)
提交回复
热议问题