Prevent html input type=number from ever being empty
HTML5 validation rules will only help when the form is submitted. If you want to prevent the input from being empty you'll need to use some JS.
The following (not "ugly JS hack") will work for all number
inputs on a page and insert a value of 0
if the user tries to leave the input empty.
const numInputs = document.querySelectorAll('input[type=number]')
numInputs.forEach(function(input) {
input.addEventListener('change', function(e) {
if (e.target.value == '') {
e.target.value = 0
}
})
})
<input type="number" required value="0" />
<input type="number" required value="0" />
So use HTML5 validation. Will not submit unless it is valid.
input:invalid {
border: 1px solid red;
}
input:valid {
border: 1px solid green;
}
<form>
<label for="num">Pick a number?</label>
<input id="num" name="number" type="number" value="0" min="0" required>
<button>Submit</button>
</form>