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

前端 未结 26 2851
感动是毒
感动是毒 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:21

    You can specify the min and max attributes, which will allow input only within a specific range.

    
    
    

    This only works for the spinner control buttons, however. Although the user may be able to type a number greater than the allowed max, the form will not submit.

    Chrome's validation message for numbers greater than the max
    Screenshot taken from Chrome 15

    You can use the HTML5 oninput event in JavaScript to limit the number of characters:

    myInput.oninput = function () {
        if (this.value.length > 4) {
            this.value = this.value.slice(0,4); 
        }
    }
    

提交回复
热议问题