How to force Input field to enter numbers only using JavaScript ? - GeeksforGeeks

20 Jul, 2021
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices. There are so many other ways to force the input field to take input only numbers.
The following examples will explain how to force input field force numbers. 
By using ASCII code
By using replace(), isNan() function
Example 1: Example below illustrate Input[type=”text”] allow only Numeric Value using Javascript with the help of ASCII code. 
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">    <meta name="viewport"           content="width=device-width, initial-scale=1">    <style>        div {            width: 400px;            height: 130px;            border: 2px solid black;            padding: 15px;            position: absolute;            left: 27%;        }    </style></head>  <body>    <center>        <h1 style="color:green;padding:13px;">          GeeksforGeeks        </h1>        <h3>          Force input field to take only numbers as an input        </h3>    </center>      <div class="container">        <form name="inputnumber"               autocomplete="off">            <b>Register No:</b>            <input type="text"                    onkeypress="return onlyNumberKey(event)"                    maxlength="11"                    size="50%" />              <br>            <br>            <b>Ph. Number:</b>            <input type="tel"                    size="50%"                    onkeypress="return onlyNumberKey(event)" />              <br>            <br>            <center>                <b>Age:</b>                <input type="number"                        placeholder=" Only 12+ allowed"                        min="12" />                <input type="submit"                       value="Submit"                        onclick="return detailssubmit()">            </center>        </form>    </div></body><script>    function onlyNumberKey(evt) {                  // Only ASCII character in that range allowed        var ASCIICode = (evt.which) ? evt.which : evt.keyCode        if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))            return false;        return true;    }</script><script>    function detailssubmit() {        alert("Your details were Submitted");    }</script>  </html>
Output:  
Example 2: Example below illustrates Input[type=”text”] allow only Numeric Value using Javascript with the help of jQuery’s replace() method and javascript’s isNaN()function.
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">    <meta name="viewport" content=            "width=device-width, initial-scale=1">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">    </script></head>  <body>    <center>        <h1 style="color:green;padding:13px;">         GeeksforGeeks</h1>        <h3>            Input[type=text] allow only            Numeric Value Example        </h3>        <br>          <form autocomplete="off" id="form1">            <b>Enter 4-digit Pin:</b>            <input type="text" name="numonly"                   maxlength="4">            <br>            <br>              <b>Enter passkey:</b>            <input type="text" name="passkey"                   id="num"                    oninput="return onlynum()"                   minlength="2">        </form>      </center></body><script>    $(function() {        $("input[name='numonly']").on('input', function(e) {            $(this).val($(this).val().replace(/[^0-9]/g, ''));        });    });</script><script>    function onlynum() {        var fm = document.getElementById("form2");        var ip = document.getElementById("num");        var tag = document.getElementById("value");        var res = ip.value;          if (res != '') {            if (isNaN(res)) {                                  // Set input value empty                ip.value = "";                                  // Reset the form                fm.reset();                return false;            } else {                return true            }        }    }</script>  </html>
Output: 
 
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
clintra
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference between var, let and const keywords in JavaScript
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers