
In this tutorial, I will teach you to accept only the number and digits using jQuery.
Generally, when you enter OTP then you need to be accepted only digits and other criteria you need to accept only text only.
So, let’s start our tutorial
Create an HTML file
Create an HTML file name is a number.html and put the below code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#number").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#numbermsg").html("Number only accept here!").show().fadeOut("slow");
return false;
}
});
$('#words').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
$("#wordsmsg").html("Words only accept here!").show().fadeOut("slow");
return false;
}
}
});
});
</script>
</head>
<body>
Number : <input type="text" name="number" id="number" /> <span id="numbermsg"></span>
<br>
Text : <input type="text" name="words" id="words" /> <span id="wordsmsg"></span>
</body>
<style type="text/css">
#numbermsg{
color: green;
}
#wordsmsg{
color: orange;
}
</style>
</html>
I hope it will help you!