Insert Only Numbers Using jQuery

Today i will tell you how to make custom validation using jQuery, this validation allows only numbers to insert in the input field.

Demo: https://jsfiddle.net/javedfiddle/g9z57pew/

HTML

<input type="text" name="numbers" class="numbers" placeholder="Enter Only Numbers" />

JQuery

$(".numbers").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
return false;
}
});

Complete Webpage

<html>
<head>
<title>Insert Only Numbers Using jQuery</title>
</head>
<body>
<input type="text" name="numbers" class="numbers" placeholder="Enter Only Numbers" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(".numbers").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
return false;
}
});
</script>
</body>
</html>

Demo: https://jsfiddle.net/javedfiddle/g9z57pew/

Leave your comments and share this tutorial with your friends, if you find this tutorial helpful. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s