Sometimes, we want to restrict input to allow only numbers and decimal points with JavaScript.
In this article, we’ll look at how to restrict input to allow only numbers and decimal points with JavaScript.
How to restrict input to allow only numbers and decimal points with JavaScript?
To restrict input to allow only numbers and decimal points with JavaScript, we check the keyCode
value.
For instance, we write
<input type="text" onkeypress="return isNumberKey(this, event);" />
to add the input.
We set its onkeypress
attribute to isNumberKey(this, event)
to call isNumberKey
with the input and the event object.
Next we write
function isNumberKey(txt, evt) {
const charCode = evt.keyCode;
if (charCode === 46) {
if (txt.value.indexOf(".") === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
}
return true;
}
to define the isNumberKey
function.
In it, we check the key pressed with thge keyCode
property.
We return true
if the key pressed is the one we want and return false
otherwise.
Conclusion
To restrict input to allow only numbers and decimal points with JavaScript, we check the keyCode
value.