Prevent user from typing in input at max value

2020-02-25 23:31发布

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').keyup(function(e){
        if ($(this).val() > 100) {               
           e.preventDefault();                
        }
    });

To confirm I want the value not the string length, and it can't be above 100.

However this is not preventing further input in the field. What am I missing.

8条回答
SAY GOODBYE
2楼-- · 2020-02-26 00:19
<input class="equipCatValidation" />
var maxValue = 100;

jquery

$('.equipCatValidation').on('keypress', function(e){
  /* preventing set value when it doesn't pass conditions*/
 e.preventDefault(); 
 var input = $(this);
 var value = Number(input.val());
 var key = Number(e.key);
 if (Number.isInteger(key)) {
     value = Number("" + value + key);
     if (value > maxValue) {
       return false;
     }
     /* if value < maxValue => set new input value 
     in this way we don't allow input multi 0 */
     $element.val(value);
 }
});

vanilla js

document.querySelector(".equipCatValidation")
 .addEventListener("keypress", function(e) {
  e.preventDefault();
  var input = e.target;
  var value = Number(input.value);
  var key = Number(e.key);
  if (Number.isInteger(key)) {
    value = Number("" + value + key);
    if (value > maxValue) {
      return false;
    }
    input.value = value;
  }
 });

example

addition to the this answer

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-26 00:20

Maybe keydown instead of keyup?

<!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  <script>
  $(function() {

    $('.equipCatValidation').keydown(function(e){
      if ($(this).val() > 100) {            
         e.preventDefault();              
      }
    });

  })
  </script>

</head>
<body>

<input type="text" class="equipCatValidation">

</body>
</html>

EDIT: There is a valid comment here - Prevent user from typing in input at max value - to circumvent that you should probably store the previous value and restore it when necessary.

查看更多
登录 后发表回答