How to Allow Only 4-digit Numbers in Textbox using JQuery?

Posted by

Introduction

Have you ever wanted to restrict the input in a textbox to only allow 4-digit numbers? In this tutorial, we will explore how to achieve this using JQuery, a popular JavaScript library. By following the steps below, you will be able to enhance the user experience on your website by ensuring that users can only enter valid 4-digit numbers.

Step:- Create a HTML Page

<!DOCTYPE html>
<html>
<head>
    <title>Allow only 4 numbers in textbox using Jquery - wizbrand</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body> 
    
<form>
  <h1>Allow only 4 numbers in textbox using Jquery - wizbrand</h1>
  <input type="text" name="phone" placeholder="4-digit numbers" maxlength="4" class="phone">
     
  <button type="submit">Submit</button>
</form>
    
</body>
    
<script type="text/javascript">
  $('.phone').keypress(function(e) {
      var arr = [];
      var kk = e.which;
   
      for (i = 48; i < 58; i++)
          arr.push(i);
   
      if (!(arr.indexOf(kk)>=0))
          e.preventDefault();
  });
</script>
</html>

Output:-

Hopefully, It will help you to set a password..!!!

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x