Credit/Debit Card Details Capture Textbox in ASP.NET using JavaScript

Description: We have to design a pair of 4 textboxes that capture the details of a credit/debit card, which is 16 digits. The functionality that we want to provide is that when the 4 value in the 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 NuGet package manager.
Step 3: Add the following code to it.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo.aspx.cs" Inherits="CreditCardDetailsCaptureTextBox.demo" %>
 
 
<!DOCTYPE html>
 
<html>
<head runat="server">
    <title>Credit Card Details Capture using JavaScript</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <script type="text/javascript">
        function moveFocus(from, to) {
            var length = from.value.length;
            var maxLength = from.getAttribute("maxLength");
            if (length == maxLength) {
                document.getElementById(to).focus();
            }
        };
    </script>
</head>
<body class="container-fluid">
    <form id="form1" runat="server">
        <div id="creditCardDetailsTextboxes" class="jumbotron">
            Enter Card Number:
            <asp:TextBox ID="TextBox1" runat="server"  MaxLength="4" Width="50px" onkeyup="moveFocus(this,'TextBox2')"></asp:TextBox>
            <asp:TextBox ID="TextBox2" runat="server"  MaxLength="4" Width="50px" onkeyup="moveFocus(this,'TextBox3')"></asp:TextBox>
            <asp:TextBox ID="TextBox3" runat="server"  MaxLength="4" Width="50px" onkeyup="moveFocus(this,'TextBox4')"></asp:TextBox>
            <asp:TextBox ID="TextBox4" runat="server"  MaxLength="4" Width="50px"></asp:TextBox>
        </div>
    </form>
</body>
</html>


Step 4 :Below is the explanation of the above mentioned code.


Step 5:When you press F5, you will the following window.

If you like this trick, please share among your friends.You can also view this tutorial on my personal blog, technewsinform.

Advertisements