How would I make it so that I can allow a ‘-‘ (negative sign) before the number which would bypass the max 4 digit limit?
Currently, if I use a ‘-‘, only 3 digits can be entered, while I need it to allow 4 digits.
// Only Numbers can be Entered
function fNumOnly(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode >= 48 && charCode <= 57) || charCode == 45) {
return true;
}
return false;
}
<input id="txtFahrenheit" type="text" onkeypress="return fNumOnly(event);" maxlength="4" />
Why not use <input type="number"> with min and max values? For example:
input:valid {
border-color: green;
}
input:invalid {
border-color: red;
}
<div>Enter a number between -9999 and 9999 (green for valid entry, red for invalid entry)</div>
<input type="number" name="num" min="-9999" max="9999" required>
You can check length of value of input using regex.
function fNumOnly(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (
((charCode >= 48 && charCode <= 57) || charCode == 45) &&
evt.target.value.match(/^-?\d{0,3}$/g)
) {
return true;
}
return false;
}
<input id="txtFahrenheit" type="text" onkeypress="return fNumOnly(event);" />
Also you can use type=number and min&max attribute for input instead of checking charCode in function
function fNumOnly(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (evt.target.value.match(/^-?\d{0,3}$/g))
return true;
return false;
}
<input id="txtFahrenheit" type="number" onkeypress="return fNumOnly(event);" min="-9999" max="9999"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With