ItSolutionStuff.com

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

By Hardik Savani • July 4, 2023
jQuery

If you need to add jquery validation for your textbox like textbox should accept only numbers values on keypress event. you can also use keyup or keypress event to allow only numeric values in textbox using jquery.

we will use keyCode for prevent to add string values. we will also accept numbers in textbox using jquery.

I want to write very simple and full example so you can understand how it is working this example. you can also check demo. i will attach demo link to bottom so you can check it. let' see bellow full example:

Example:

<!DOCTYPE html>

<html>

<head>

<title>JQuery - Allow only numeric values (numbers) in Textbox - ItSolutionStuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

</head>

<body>

<div class="container">

<h1>JQuery - Allow only numeric values (numbers) in Textbox - ItSolutionStuff.com</h1>

<label>Enter Value:</label>

<input type="text" name="myValue" class="only-numeric" >

<span class="error" style="color: red; display: none">* Input digits (0 - 9)</span>

</div>

<script type="text/javascript">

$(document).ready(function() {

$(".only-numeric").bind("keypress", function (e) {

var keyCode = e.which ? e.which : e.keyCode

if (!(keyCode >= 48 && keyCode <= 57)) {

$(".error").css("display", "inline");

return false;

}else{

$(".error").css("display", "none");

}

});

});

</script>

</body>

</html>

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

JQuery Remove Multiple Values from Array Example

Read Now →

Calculate Number of Days Between Two Dates in JQuery

Read Now →

JQuery Get Days Difference Between Two Dates Example

Read Now →

How to Disable F5 Refresh Button using JQuery?

Read Now →

Add Edit Delete Table Row Example using JQuery

Read Now →

How to Disable Browser Back Button using JQuery?

Read Now →

How to Get Selected Checkbox Value from Checkboxlist using JQuery?

Read Now →

JQuery Disable Right Click, Cut, Copy and Paste Example

Read Now →

Jquery Ajax Form Validation with Laravel 5.8

Read Now →

JQuery Rotate Image Animation Example Code

Read Now →

How to Remove Duplicate Value from Array in JQuery?

Read Now →

How to Create Custom Scrollbar using JQuery?

Read Now →

JQuery Draggable Sortable Table Rows Example

Read Now →

How to Convert Line Breaks to br in jQuery ?

Read Now →