How to restrict number of characters that can be e

2019-01-22 08:06发布

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

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

Instead of limiting the number of digits or the value of the number entered, the number is just left as it was typed in on iPhone 4. This markup works on most other phones we tested.

What gives?

Any workarounds?

If it is important to the solution, we use jQuery mobile.

Thanks!

10条回答
冷血范
2楼-- · 2019-01-22 08:37

Another option with jQuery, but onkeypress event... ;)

$("input[type=number]").on('keypress',function(e) { 
    var $that = $(this),
    maxlength = $that.attr('maxlength')
    if($.isNumeric(maxlength)){
        if($that.val().length == maxlength) { e.preventDefault(); return; }

        $that.val($that.val().substr(0, maxlength));
    };
});
查看更多
狗以群分
3楼-- · 2019-01-22 08:37

you can use this code:

<input type="number" maxlength="2" min="0" max="99"
       onkeypress="limitKeypress(event,this.value,2)"/>

and js code:

function limitKeypress(event, value, maxLength) {
    if (value != undefined && value.toString().length >= maxLength) {
        event.preventDefault();
    }
}
查看更多
Melony?
4楼-- · 2019-01-22 08:37

This is Tripex answer optimized for allowing delete key, works when typing and on paste.

$(document).on("keyup", "#your_element", function(e) {
    var $that = $(this),
    maxlength = $that.attr('maxlength');
    if ($.isNumeric(maxlength)){
        if($that.val().length === maxlength) {
            e.preventDefault();
            // If keyCode is not delete key 
            if (e.keyCode !== 64) {
                return;
            }
        }
        $that.val($that.val().substr(0, maxlength));
    }
});
查看更多
冷血范
5楼-- · 2019-01-22 08:41

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" />
查看更多
登录 后发表回答