How to Allow Only Numeric Input with a Decimal Point Using jQuery

Last updated 1 month ago | 58 views 75     5

Tags:- HTML JQuery

When building web forms, ensuring proper data validation is crucial. One common requirement is to allow only numeric input with an optional decimal point. This can be easily achieved with jQuery.

✅ HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Numeric Input Only</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <h2>Numeric Input with Decimal Point</h2>
  <input type="text" id="numericInput" placeholder="Enter numbers only">

  <script>
    $(document).ready(function() {
      $('#numericInput').on('input', function() {
        let value = $(this).val();
        // Allow only numbers and a single decimal point
        if (!/^\d*\.?\d*$/.test(value)) {
          $(this).val(value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1'));
        }
      });
    });
  </script>
</body>
</html>

Explanation

  1. Regular Expression Check (^\d*\.?\d*$): Allows digits and a single decimal point.

  2. Replace Invalid Characters: Removes any non-numeric characters except the decimal point.

  3. Prevent Multiple Decimal Points: Ensures only one decimal point is allowed.


✅ Benefits

  • Prevents the user from entering invalid characters.

  • Supports decimal numbers without allowing multiple decimal points.

By implementing this approach, you can enhance the accuracy and reliability of numeric data entry on your web forms.