How to Only Allow Numbers in a Text Box using jQuery?


We can easily allow only numbers in a textbox using jQuery. Under the keyup() set the code for allowing only number values so that the textbox never accept strings. We will see two examples −

  • Allow Only Numbers in a TextBox using jQuery replace()
  • Allow Only Numbers in a TextBox using jQuery fromCharCode()

Allow Only Numbers in a TextBox using jQuery replace()

In this example, we will see how to allow only numbers in a TextBox using jQuery replace(). We must set the code under the keyup to allow only numbers while typing, else the textbox will not allow typing strings −

$('.numbers').keyup(function () {
   this.value = this.value.replace(/[^0-9\.]/g,'');
});

Above, we have set a Regex that only allows number 0-9 to be typed in the textbox. The .numbers is a class set for both the inputs i.e. −

<p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p>

Example

Let us now see the complete example to allow only numbers in a TextBox using jQuery replace() −

<!DOCTYPE html> <html> <title>Input Numbers Only</title> <head> <script src="https://code.jquery.com/jquery-git.js"></script> </head> <body> <h1>Score</h1> <p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p> <script> $('.numbers').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,''); }); </script> </body> </html>

Output

The above textboxes only allow number input.

Allow Only Numbers in a TextBox using jQuery fromCharCode()

In this example, we will allow only numbers in a TextBox using jQuery fromCharCode(). We must set the code under the keypress to allow only numbers while typing, else the textbox will not allow typing strings −

$('.numbers').keypress(function (e) {
   if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

Above, we have set a Regex that only allows number 0-9 to be typed in the textbox. The .numbers is a class set for both the inputs i.e. −

<p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p>

Example

Let us now see the complete example to allow only numbers in a TextBox −

<!DOCTYPE html> <html> <title>Input Numbers Only</title> <head> <script src="https://code.jquery.com/jquery-git.js"></script> </head> <body> <h1>Score</h1> <p>Rank: <input type="text" class="numbers" value="" /> </p> <p>Marks: <input type="text" class="numbers" value="" /> </p> <script> $('.numbers').keypress(function (e) { if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false; }); </script> </body> </html>

Output

Updated on: 22-Nov-2022

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements