One-Time Passwords (OTPs) are commonly used for user authentication and verification in various applications. Implementing a secure and user-friendly OTP input field is crucial for providing a seamless authentication experience. In this tutorial, you will learn how to create an OTP input field using HTML, CSS, and JavaScript.
Steps to Build OTP Input Field Using HTML, CSS & JavaScript
Step 1: Create HTML Structure
Start by creating the HTML structure for the OTP input field. In this example, we’ll use a form with an input field for each digit of the OTP:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OTP Input Field Example</title>
<style>
/* Optional: Styling for demonstration purposes */
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
#otpForm {
display: flex;
}
.otpInput {
width: 40px;
height: 40px;
font-size: 18px;
text-align: center;
margin: 0 5px;
}
</style>
</head>
<body>
<form id="otpForm">
<input type="text" class="otpInput" maxlength="1">
<input type="text" class="otpInput" maxlength="1">
<input type="text" class="otpInput" maxlength="1">
<input type="text" class="otpInput" maxlength="1">
</form>
<script>
// JavaScript code will go here
</script>
</body>
</html>
In this example, we have a form (otpForm) containing four input fields (otpInput) to capture each digit of the OTP.
Step 2: Implement JavaScript to Handle Input Fields
Here is the JavaScript code that handles the OTP input logic. Put this code in the <script>
tag of the index.html
.
document.addEventListener('DOMContentLoaded', function () {
const otpInputs = document.querySelectorAll('.otpInput');
// Function to focus on the next input field
function focusNext(currentInput) {
const maxLength = parseInt(currentInput.maxLength, 10);
const currentInputIndex = Array.from(otpInputs).indexOf(currentInput);
if (currentInput.value.length === maxLength) {
// Move focus to the next input field
const nextInput = otpInputs[currentInputIndex + 1];
if (nextInput) {
nextInput.focus();
} else {
// Submit the form or trigger another action when all inputs are filled
console.log('OTP Entered:', getOTP());
}
}
}
// Function to focus on the previous input field
function focusPrevious(currentInput) {
const currentInputIndex = Array.from(otpInputs).indexOf(currentInput);
if (currentInput.value.length === 0) {
const previousInput = otpInputs[currentInputIndex - 1];
if (previousInput) {
previousInput.focus();
}
}
}
function getOTP() {
// Concatenate values of all input fields to get the complete OTP
return Array.from(otpInputs).map(input => input.value).join('');
}
// Add event listeners for input and keydown events
otpInputs.forEach(input => {
input.addEventListener('input', function () {
focusNext(this);
});
input.addEventListener('keydown', function (event) {
if (event.key === 'Backspace') {
focusPrevious(this);
}
});
});
});
Here’s an explanation of the JavaScript code:
- The
focusNext
function is called when a digit is entered into an input field. It checks if the input field is filled to its maximum length and moves the focus to the next input field. If there is no next input field, it can trigger another action, such as submitting the form or verifying the OTP. - The
getOTP
function is used to concatenate the values of all input fields and return the complete OTP. - The
focusPrevious
function is introduced to move the focus to the previous input field when the Backspace key is pressed with an empty input. - Event listeners are added to each input field for both the
input
andkeydown
events. - The “keydown” event listener checks if the Backspace key is pressed and, if so, calls the
focusPrevious
function.
Step 3: Test the OTP Input Fields
When you run this HTML file in a browser, you can enter digits into the OTP input fields, and the focus will automatically move to the next field once a digit is entered.
Use the Backspace key to move the focus back to the previous field, allowing you to correct or remove digits The complete OTP will be logged to the console when all fields are filled.