Loading...

TapGen

Free online tutorials

img

In this article, we will learn How to make an HTML input field to enter numbers only using JavaScript. 

To create an HTML text input that only allows numeric values, you can use several approaches.

Here are a few common methods: 

Example 01: Here is an example that allows for exactly one decimal, but no more. 

You will create an <input> element with the oninput attribute set to a JavaScript function that validates and sanitizes the input.

Example

                                        
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Numeric Input</title>
    <style>
        /* Optional: Style the input for better visibility */
        input {
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <label for="numericInput">Enter a number:</label>
    <input type="text" id="numericInput" name="numericInput" oninput="validateNumericInput(this)" />

    <script>
        function validateNumericInput(input) {
            // Replace all non-numeric characters with an empty string
            input.value = input.value.replace(/[^0-9.]/g, '');
        }
    </script>
</body>
</html>
 
 

Output:

You can also use the code simply in oninput attribute 

Example

                                        
 <!DOCTYPE html>
<html>
<head>
    
</head>
<body>
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />
 
</body>
</html>
 
 

 

Using <input type="number">

 

The simplest way to restrict input to numeric values is to use the type="number" attribute in your <input> element.

This restricts the input to numeric values and provides a spinner for adjusting the value.

Example

                                        
                                            <input type="number" id="numericInput" name="numericInput" min="0" max="100" step="0.01">
 
                                    

attributes you might use with <input type="number">:

  • min and max: Define the range of acceptable values.
  • step: Define the step interval for values (e.g., 0.01 for decimals).

 

Thanks!

=================================
Share This Article
icon

New to Communities?

Join the community