Reputation: 1157
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" />
Upvotes: 0
Views: 79
Reputation: 534
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>
Upvotes: 0
Reputation: 4005
Just change event to onkeyup
:
<input id="xxx" type="number" onkeyup="maxValCheck()" max="5" min="1" value="1"/>
Upvotes: 1