I have the following code in my index.html for an input field:
<input id="inpMinutes" type="number" style="width: 50px; text-align: right" min="1" value="1" onkeypress="return isNumberKey(event)" />
<span id="minuteS">minute</span>
I want to keep the entered number between 1 and 600 without allowing entering any non digit characters. This is done by 2 different functions in my main.js file, but I would like to merge them, but I am very noob at javascript, I just stole and modified this code.
// keep out non-digits from the input field that calls this
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
$("#inpMinutes").on("input", function() {
// do not allow to enter a number less than 1 into the minutes field (minus sign is prevented by isNumberKey())
if ( this.value == 0 ) {
this.value = 1;
// do not allow to enter a number larger than 600
} else if ( this.value > 600 ) {
this.value = 600;
}
// make the "minute" word grammatically correct
if ( this.value > 1 ) {
minuteS.innerHTML = "minutes";
} else {
minuteS.innerHTML = "minute";
}
});
What is the most elegant (most efficient?) way to merge these into one single function? Thanks in advance.
type=numberto make (some) browsers enforce the numbers itself, and always validate yourself. Still, this is not guaranteed, so you should validate again on 'input', and also validate again on the server. Life is a female dog...