Welcome back again, In this JavaScript tutorial, we will discuss how to create an input form that only allows inputting numbers that can be typed into this form. If the user types a letter or other character, it will not work or what is input will not work or what is inputted will not appear on the input form. So the form we are going to create is a form that only accommodates numbers. Henceforth, friends can listen to the tutorial on how to make input only numbers using the following javascript.
Making Input Only Numbers with Javascript
Sometimes in creating an application or website, we are required to create an input form that only allows inputting numbers. This aims to minimize errors in an application that we make. For how to make number validation using javascript, friends, please pay attention to the following explanation.
Make an html or php file up to your themes. Here I provide a file with number.html where in this file we will validate numbers or make validation just numbers with javascript. First, we will create a form, friends.
Try friends, pay attention to the example syntax for creating a number input form above. First we first create a regular form.
<input type="text" onkeypress="return hanyaAngka(event)">
But in this form we give an onkeypress
event. To make an action when this form is typed or inputted. So when typing occurs in this form, the function is run only()
.
onkeypress="return hanyaAngka(event)"
Also returns the value of this function.
Furthermore, friends, pay attention to the function only().
function hanyaAngka(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Here we check if what is inputted is a number, it will return true in the form.
if (charCode > 31 && (charCode < 48 || charCode > 57))
Now try running it in a browser.
Only numbers can be input.
How to make the maximum number of digits entered?
To make the maximum number entered, you just need to add the maxlength attribute to the form element. example.
<input type="text" maxlength="2" onkeypress="return hanyaAngka(event)"/>
well, in the example above it means that we only allow 2 digit numbers to be input. Furthermore, you will not be able to type again on the form.
Conclusion
Okay friends, that's enough for the tutorial, hopefully it's useful for your themes, if you have trouble, you can ask by filling in the comments column.
Top comments (0)