Prevent user from typing in input at max value

前端 未结 7 1954
遥遥无期
遥遥无期 2020-12-30 04:41

I\'d like the user to be blocked from typing more if the value is over 100. So far I have the following from reading different posts:

$(\'.equipCatValidation         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 05:22

    Here's a solution for those using modern vanilla Javascript:

    Just snap the value back down to the max when the user focuses away from the input.

    You would set the input to a number type and the max value

    
    

    and then add a function to the onblur method of the element

    document.querySelector('input[max]').onblur = function (event) {
        // If the value is less than the max then stop
        if (Number(event.target.value) < event.target.max) return
        // Snap the value to the max
        event.target.value = event.target.max
    }
    

    You can also use oninput instead of onblur but that may cause the user to have to fight the input in certain situations.

    Example

提交回复
热议问题