<!DOCTYPE html>
<html>
<head>
<title>Empty</title>
<meta charset="UTF-8">
</head>
<body>
<input type="text" value="1" id="count">
<button type="button" id="increase">+1</button>
<button type="button" id="decrease">-1</button>
<script>
let previous_value = null
const count_field = document.querySelector("input#count")
const increase_button = document.querySelector("button#increase")
const decrease_button = document.querySelector("button#decrease")
const is_range_exceeded = (value, max = 1000) => {
if (value < 1 || value > max) {
return true
}
return false
}
increase_button.addEventListener("click", () => {
let value = Number(count_field.value)
if (is_range_exceeded(value + 1)) {
// Do something when exceeded
console.log(`${value + 1} not allowed`)
return null
}
count_field.value = value + 1
})
decrease_button.addEventListener("click", () => {
let value = Number(count_field.value)
if (is_range_exceeded(value - 1)) {
// Do something when exceeded
console.log(`${value - 1} not allowed`)
return null
}
count_field.value = value - 1
})
count_field.addEventListener("input", () => {
let value = Number(count_field.value)
if (is_range_exceeded(value)) {
// Do something when exceeded
console.log(`${value} not allowed`)
count_field.value = previous_value
return null
}
previous_value = value
})
</script>
</body>
</html>