Allow only numeric (0-9) in inputbox | jQuery?

Allowing numbers only in a text box using jQuery involves capturing user input events and validating the input against numeric patterns.

HTML Structure

Create an HTML input element where you want to restrict input to numbers.

<input type="text" id="numberInput" placeholder="Enter numbers only">

jQuery Input Event

Use jQuery to bind an input event handler to the text box.

$(document).ready(function() { $("#numberInput").on("input", function() { // Your code to validate input goes here }); });

Validation with Regular Expression

Inside the input event handler, use a regular expression to validate the input. The regular expression /^[0-9]*$/ checks if the input contains only numeric characters.

$(document).ready(function() { $("#numberInput").on("input", function() { var inputVal = $(this).val(); if (!/^[0-9]*$/.test(inputVal)) { $(this).val(""); // Clear input if non-numeric characters are entered } }); });

In this example, the input event is triggered whenever the user types or pastes content into the text box with the ID "numberInput". The regular expression /^[0-9]*$/ checks if the input consists solely of numeric characters. If the input contains non-numeric characters, the content of the text box is cleared.

Full Source | jQuery

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Allow Numbers Only</title> <!-- Add jQuery script link --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="container mt-5"> <input type="text" id="numberInput" placeholder="Enter numbers only"> </div> <script> $(document).ready(function() { $("#numberInput").on("input", function() { var inputVal = $(this).val(); if (!/^[0-9]*$/.test(inputVal)) { $(this).val(""); // Clear input if non-numeric characters are entered } }); }); </script> </body> </html>

Conclusion

To restrict a text box to accept only numeric input using jQuery, you can employ the input event handler. By validating the input against a numeric regular expression (/^[0-9]*$/), you can clear the text box if non-numeric characters are entered. This approach ensures that the user can only input numbers, enhancing data integrity and user experience.