Prevent user from typing in input at max value

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

    Checking keyup is too late, the event of adding the character has already happened. You need to use keydown. But you also want to make sure the value isn't > 100 so you do need to also use keyup to allow js to check the value then too.

    You also have to allow people to delete the value, otherwise, once it's > 100 nothing can be changed.

    
    

    When using input type="number", change also needs to be on the event list.

    $('.equipCatValidation').on('keydown keyup change', function(e){
        if ($(this).val() > 100 
            && e.keyCode !== 46 // keycode for delete
            && e.keyCode !== 8 // keycode for backspace
           ) {
           e.preventDefault();
           $(this).val(100);
        }
    });
    

    http://jsfiddle.net/c8Lsvzdk/

提交回复
热议问题