skip to Main Content

For example, if the input is 10 and the user types 1, the detected value becomes 101, which is greater than 50. The value is then set to 50, but on the next detection, it changes to 501 instead of staying at 50.

const inputElement = document.getElementById('myInput');
console.log('The output I get is:')
inputElement.addEventListener('input', function(event) {
  let value = Number(event.target.value)
  console.log("value:" + value)
  if (value > 50) {
    event.target.value = 50
    console.log("It cannot be greater than 50");
  }
});
<input type="text" id="myInput" placeholder="Type something...">

My input is:’1′ -> ‘2’ -> ‘3’;

The output I get is:
value:1
value:1
value:12
value:12
value:123
It cannot be greater than 50
value:503
It cannot be greater than 50

2

Answers


  1. This is the expected behavior, since you cannot prevent the user from typing (from the keyboard) a number or other text.
    First, you read the text entered by the user, and then, if it is larger than the maximum, you change it (‘501′ becomes ’50’)

    Login or Signup to reply.
  2. const inputElement = document.getElementById('myInput');
    
    inputElement.addEventListener('input', function(event) {
      let value = Number(event.target.value);
      if (value > 50) {
        event.target.value = 50;
        console.log("It cannot be greater than 50");
      } else {
        console.log("value:" + value);
      }
    });
    <input type="text" id="myInput" placeholder="Type something...">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search