How can I limit possible inputs in a HTML5 “number” element?

前端 未结 26 2809
感动是毒
感动是毒 2020-11-22 05:12

For element, maxlength is not working. How can I restrict the maxlength for that number element?

26条回答
  •  迷失自我
    2020-11-22 05:16

    I had this problem before and I solved it using a combination of html5 number type and jQuery.

    
    

    script:

    $("input[name='minutes']").on('keyup keypress blur change', function(e) {
        //return false if not 0-9
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
           return false;
        }else{
            //limit length but allow backspace so that you can still delete the numbers.
            if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
                return false;
            }
        }
    });
    

    I don't know if the events are a bit overkill but it solved my problem. JSfiddle

提交回复
热议问题