Prevent user from typing in input at max value

前端 未结 7 1933
遥遥无期
遥遥无期 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:24

    Basically keypress events are fired before accepting the current value. So when you press on any key, keypress event is subscribed but you don't get the updated value/result for the recently pressed key. So, to get the last pressed key we can use the fromCharCode method and concat it with the value we got from the textbox. That's it,

    HTML :

    
    

    jQuery :

    $("#inputBox").on("keypress", function(e){
        var currentValue = String.fromCharCode(e.which);
        var finalValue = $(this).val() + currentValue;
        if(finalValue > 100){
            e.preventDefault();
        }
    });
    

    jsFiddle

提交回复
热议问题