Allow only numbers to be typed in a textbox

Allow only numbers to be typed in a textbox

Here, we will show how you can allow only numbers to be typed in a textbox. This is some time requirement to only need numbers in textbox.

First we create html for enter number in textbox.

				
					<!DOCTYPE html>
<html>
  <head>
    <title>Allow only numbers to be typed in a textbox using html, javascript</title>   
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
  </head>
  <body>
        <h3 align="center">Allow only numbers to be typed in a textbox using html, javascript</h3>
        <br />
                    <label>Contact Number</label>          
                    <input type="text" name = "contact_number" id = "contact_number"  value="" onkeypress="javascript:return isNumber(event)">
  </body>
</html>
				
			

Above code we use onkeypress javascript event.

Below is javascript code for validate typed characters in numbers.

				
					function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
				
			

I hope this article helps you.
Thanks for visiting Inflay.com .