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

前端 未结 10 1459
野趣味
野趣味 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:31

    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));
        }
    });
    

提交回复
热议问题