Allow Only Numeric Values in Textbox using JQuery

May 21, 2020 | Category : JQuery

In this article we will cover on how to implement jquery allow numeric only. if you have question about allow only numbers in textbox jquery on keyup then i will give simple example with solution. This article will give you simple example of textbox accept only numbers in jquery. i explained simply about textbox should accept only numbers using jquery. Let's get started with jquery allow only numbers on keypress.

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 - HDTuto.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 - HDTuto.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...