0

If user types in a value more than 5, I want to set it to 5.

function maxValCheck() {
  if (document.getElementById('xxx').value > 5) {
    document.getElementById('xxx').value = 5;
  }
}
<input id="xxx" type="number" onkeypress="maxValCheck()" max="5" min="1" value="1" />

4
  • 2
    change event to onkeyup Commented Jun 24, 2019 at 6:24
  • 1
    What is wrong with the code you have provided? What errors are you getting? What isn't happening that should? What is happening that shouldn't? Commented Jun 24, 2019 at 6:24
  • 1
    function maxValCheck(fld) { if (fld.value > 5) { fld.value = 5; } } works too and is a better event if you pass the field: oninput="maxValCheck(this)" Commented Jun 24, 2019 at 6:26
  • 1
    stackoverflow.com/questions/10911047/keydown-event-new-value Commented Jun 24, 2019 at 7:07

2 Answers 2

1

Just change event to onkeyup:

<input id="xxx" type="number" onkeyup="maxValCheck()" max="5" min="1" value="1"/>
Sign up to request clarification or add additional context in comments.

2 Comments

You just suggested what?
oninput is a better event
0

You can select the element by getElementById or from the querySelector and need to specify the event that you're going to trigger as the first parameter and second parameter is the function that you're going to execute on the added method in addEventListener.

<input id="xxx" type="number" max="5" min="1" value="1" />

<script>
    const selectElement = document.querySelector('#xxx');
    selectElement.addEventListener('change', function (evt) {
        console.log("value is changing in input");
    });

    // or

    document.getElementById("xxx").addEventListener('change', function (evt) {
        console.log("value is changing in input");
    });
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.