<label>
Without min and max
<input type="number">
</label>
<label>
With min(0)
<input type="number" min="0">
</label>
<label>
With max(100)
<input type="number" max="100">
</label>
<label>
With min(0) and max(100)
<input type="number" min="0" max="100">
</label>
body {
margin: 0;
font-family: sans-serif;
}
label {
padding: 16px;
display: block;
}
input {
width: 200px;
display: block;
}
document.querySelectorAll('input[type="number"]').forEach(input => {
input.addEventListener('input', () => {
if (input.value !== '') {
const min = input.min !== '' ? Number(input.min) : -Infinity;
const max = input.max !== '' ? Number(input.max) : Infinity;
const value = Number(input.value);
input.value = Math.max(min, Math.min(value, max));
}
});
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.