To check if the inputted value is a number or letter with JavaScript, we can get the inputted value of the input element with the value
property.
Then we can use the isNaN
function to check if the inputted value is a number or not.
For instance, if we have the following form:
<form name="myForm">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
Then we can get the form and check that the age field has a number entered in it by writing:
const {
myForm
} = document.forms
myForm.addEventListener('submit', (e) => {
e.preventDefault()
const x = myForm.age.value;
if (isNaN(x)) {
alert("Must input numbers");
}
})
We get the form by its name
attribute value from document.forms
.
Then we call addEventListener
with 'submit'
to add a submit event listener to the form.
The 2nd argument is the submit event handler callback that calls e.preventDefault
to prevent default server-side submission.
Then it gets the value
of from the myForm.age
field, which is the input with name
attribute set to age
.
Next, we check if the x
string is not a number with isNaN
.
If it returns true
, then we know it’s not a number string, and we display an alert to the user with alert
.
Otherwise, it’s a number.
Conclusion
To check if the inputted value is a number or letter with JavaScript, we can get the inputted value of the input element with the value
property.
Then we can use the isNaN
function to check if the inputted value is a number or not.