Home > database >  Cannot limit <input> value in real time
Cannot limit <input> value in real time

Time:09-29

In my code, I have an HTML <input> that takes numbers and that has the following function linked to the onclick attribute:

function checkValue() {
        let sender = document.getElementById("articoli-quantita-uscita");
        let min = sender.min;
        let max = sender.max;

        let value = parseInt(sender.value);

        if (value>max) {
            sender.value = max;
        } else if (value<min) {
            sender.value = min;
        }
    }

<input class="form-control" type="number" id="articoli-quantita-uscita" name="articoli-quantita-uscita" value="1" onclick="checkValue()">

I have the function placed in a tag at the top of my body.

This function takes the input value and transforms it to the minimum or the maximum if the user inputs manually (from the keyboard and not from the input arrows) a value greater that the maximum or lower that the minimum.

Even if I have used this piece of code in other element of my WebApp and it always worked, it doesn't seem to work now, and actually the error it produces is that:

  • I type a value greater/lower than the maximum,
  • the input value doesn't change,
  • I click outside the input box ,
  • I click the input box again and the input value "refreshes" as the maximum/minimum.

Also, I set the maximum and the minimum programmatically at some point in the code from data I receive from the server, I log the maximum after I set it and it shows the correct value.

I don't understand why in this HTML page (which is very similar to the others) it doesn't work, whereas in other HTML pages in my project it does what it's supposed to.

CodePudding user response:

Change it from onclick() to onchange().

CodePudding user response:

You can use the addEventListener method to attach the event listener directly instead of using inline javascript.

You also need to listen for when the user changes the input rather than when they click on it otherwise your validation might not be applied in some situations.

The change event is good for doing that.

let sender = document.getElementById("articoli-quantita-uscita");

sender.addEventListener("input", function (event){
  let min = sender.min;
  let max = sender.max;

  let value = parseInt(sender.value);

  if (value > max) {
    sender.value = max;
  } else if (value < min) {
    sender.value = min;
  }
});
<input 
  class="form-control" 
  type="number" 
  id="articoli-quantita-uscita" 
  name="articoli-quantita-uscita" 
  value="1" 
  min="0" 
  max="10" 
  style="width: 200px"
  >

  • Related