Capture Credit/Debit Card Details In A Textbox In ASP.NET Using JavaScript

Introduction

 
We have to design a pair of 4 textboxes that capture the details of a credit/debit card, which is 16 digits always. The functionality that we want to provide is that when the 4th value in each textbox is entered, the focus of the textbox automatically moves to the next one so that no one can enter more than 4 digits in a textbox.
 
Solution 
 
This is a very simple problem, and we can easily implement using raw JavaScript.
  • Step 1: Create an empty ASP.NET web application.
  • Step 2: Add a Webform to it. Also, add Bootstrap references using the NuGet package manager.
  • Step 3: Add the following code to it.
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo.aspx.cs" Inherits="CreditCardDetailsCaptureTextBox.demo" %>    
    2.      
    3.      
    4. <!DOCTYPE html>    
    5.      
    6. <html>    
    7. <head runat="server">    
    8.     <title>Credit Card Details Capture using JavaScript</title>    
    9.     <link href="Content/bootstrap.min.css" rel="stylesheet" />    
    10.     <script type="text/javascript">    
    11.         function moveFocus(from, to) {    
    12.             var length = from.value.length;    
    13.             var maxLength = from.getAttribute("maxLength");    
    14.             if (length == maxLength) {    
    15.                 document.getElementById(to).focus();    
    16.             }    
    17.         };    
    18.     </script>    
    19. </head>    
    20. <body class="container-fluid">    
    21.     <form id="form1" runat="server">    
    22.         <div id="creditCardDetailsTextboxes" class="jumbotron">    
    23.             Enter Card Number:    
    24.             <asp:TextBox ID="TextBox1" runat="server"  MaxLength="4" Width="50px" onkeyup="moveFocus(this,'TextBox2')"></asp:TextBox>    
    25.             <asp:TextBox ID="TextBox2" runat="server"  MaxLength="4" Width="50px" onkeyup="moveFocus(this,'TextBox3')"></asp:TextBox>    
    26.             <asp:TextBox ID="TextBox3" runat="server"  MaxLength="4" Width="50px" onkeyup="moveFocus(this,'TextBox4')"></asp:TextBox>    
    27.             <asp:TextBox ID="TextBox4" runat="server"  MaxLength="4" Width="50px"></asp:TextBox>    
    28.         </div>    
    29.     </form>    
    30. </body>    
    31. </html>   
    Step 4: The following is the explanation of the above mentioned code.
     
     
    Actually, in the above code, the main magic is of the Keyup event of the textbox. When the key of the keyboard on the 4th time is up, then the JavaScript method will be called. 
     
    Step 5: When you press F5, you will see the following window.
     
     
    That's All. Hope you liked it and please share as much as you can.


    Similar Articles