Allow Only Numbers in Textbox Javascript


Allow Only Numbers in Textbox Javascript

Hi friends, today in this tutorial you will learn how to allow only numbers in textbox javascript. Also, there are other ways to do this but it will be done with the help of the javascript event handler function onkeypress() by passing an event parameter.

Also read, Google places autocomplete example using maps JavaScript API

Let us take an example below to allow only numbers in textbox javascript

<html>
<head>
<title>Allow only number in Textbox</title>
</head>
<body>
  <h3>Allow Only Number In Textbox Javascript</h3>
  <label for="fname">Quantity:</label><br>
  <input type="text" onkeypress="allowNumbers(event)">
</body>
<script type="text/javascript">
  function allowNumbers(e) {
    var code = (e.which) ? e.which : e.keyCode;
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
}
</script>
</html>

Explanation of the above example

  • After the execution of the javascript function, a conditional operator or ternary operator will be checked. The ternary operator is a kind of expression that is responsible for checking conditional statements and returning the result in a boolean value i.e. true or false based on the condition.
  • If you press alphabets from your keypad, the javascript function will run and obtain the key code. If the key code matches the numeric values as per the ASCII (American Standard Code for Information Interchange) table then it will allow you to enter the input otherwise you will be restricted to give the input and nothing will be shown in your input box.
  • The event.preventDefault() helps in restricting the user to give the input if the input does not match the numeric values based on the ASCII table.

The ASCII table is shown below for your reference.

Allow Only Numbers in Textbox Javascript

Conclusion:- I hope the above illustration will help you to understand the overview. If there is any doubt then please leave a comment below.


Leave a Comment