How to restrict number of characters that can be entered in HTML5 number input field on iPhone

前端 未结 10 1461
野趣味
野趣味 2020-12-14 02:19

It seems that neither of the \"maxlength\", \"min\" or \"max\" HTML attributes have the desired effect on iPhone for the following markup:

 

        
相关标签:
10条回答
  • 2020-12-14 02:36

    I know this question is one year old, but I don't prefer the selected answer. Because the way it works is that it shows the character that is typed and then removes it.

    In contrast I will propose another way which is similar to Will's, it is just better in the way that it prevents the character from being shown. Also I've added an else if block to check if the character is a number and then it is a good function to validate the number fields.

    HTML

    <input type="number" onkeydown="limit(this);">
    

    JS

    function limit(element)
    {
        var max_chars = 2;
        if (arguments[1].char !== "\b" && arguments[1].key !== "Left" && arguments[1].key !== "Right") {
            if (element.value.length >= max_chars) {
                return false;
            } else if (isNaN(arguments[1].char)) {
                return false;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-14 02:40

    as Andrew said you need to change the type to range, beside that you are going to have problems with IE and FF and probably old ipad browser because that's from HTML 5, and it's a "Kind New". Take a look to this person who tried the range with JS, Specify range of numbers to input in number field using javascript

    0 讨论(0)
  • 2020-12-14 02:44

    According to MDN, maxlength is not used for numbers. Have you tried just:

    <input type="number" min="0" max="99" />
    

    OR

    <input type="range" min="0" max="99" />
    
    0 讨论(0)
  • 2020-12-14 02:46

    Check this out, it works for me;

    Is there a minlength validation attribute in HTML5?

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