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>   
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
  </head>
  <body>
  
    <div class="container my-4">
        <h3 align="center">Allow only numbers to be typed in a textbox using html, javascript</h3>
        <br />
        <div class="row">
            <div class="col-md-5">
                <div class="form-group">
                    <label class="col-form-label">Contact Number<span class="text-danger"></span></label>          
                    <input type="text" class="form-control" name = "contact_number" id = "contact_number"  value="" onkeypress="javascript:return isNumber(event)">
                </div>          
            </div>
        </div>

     
    </div>

  </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 .