Otp Input Field Using HTML and CSS

3/5 - (1 vote)

Otp Input Field Using HTML and CSS

Hello guys, today in this blog we are going to create an Otp Input Field on the webpage where you can enter your OTP, this will look very great good, and we will create Otp Input Field with HTML, CSS, and JavaScript.

otp input field html css

Let’s look at the Preview Video First

Step 1: Writing the HTML code and add the basic markup for our project

Go create a file named as index.html

This code below is an HTML document that is including the Bootstrap CSS file and also an custom CSS file style.css. It is also including a JavaScript file script.js that is located at the bottom of the body tag so that the JavaScript will only load after the website is fully opened.

The Code also has an head section that includes the websites metadata, such as the character encoding and the document title.

Portfolio Website Using Html ,Css and JavaScript

The body section is containing a div element with the class of “container” which contains an h1 tag with the classes of “h3”, “text-center”, “font-weight-light”, and “mb-4”. The text of this heading says “Enter your one time password:”. Finally, there is a reference link to the JavaScript file at the bottom of the document so that the JavaScript loads after the website is fully opened.

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>CodePen - One-time password (OTP) with Bootstrap CSS and Vanilla Javascript</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css'><link rel="stylesheet" href="style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<div class="container">
  <h1 class="h3 text-center font-weight-light mb-4">Enter your one time password:</h1>
</div>
<script  src="script.js"></script>
</body>

Now we will create a form inside the div which has a class of container

This is the form that is going to contain a fieldset with two group inside which there are three input field. These input field are going to be used to enter the one time password or OTP.

Each group of input fields is enclosed in a input-group div with class “justify-content-end flex-nowrap” and “flex-nowrap” which is going to position the input fields in a row and is going to prevent them from wrapping onto the new line.

The input field is having the type of text and class of form-control form-control--otp js-otp-input. The class form-control is a Bootstrap class that styles the input fields as form controls. The class “form-control–otp” is a custom class that provides additional styling specific to OTP input fields. The class js-otp-input is used by the JavaScript code to select and manipulate the input fields.

The input fields also have other attributes such as inputmode is numeric which is specifying that the input should be a numeric value, pattern is [0-9]* which restricts the input to numeric characters only and required which specifies that the input fields must be filled out before the form can be submitted.

Finally each group of input fields is separated by a input-group-seperator div.

<form>
    <fieldset>
      <div class="d-flex align-items-center justify-content-center">
        <div class="input-group justify-content-end flex-nowrap">
          <input type="text" class="form-control form-control--otp js-otp-input" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code" required>
          <input type="text" class="form-control form-control--otp js-otp-input" inputmode="numeric" pattern="[0-9]*" required>
          <input type="text" class="form-control form-control--otp js-otp-input" inputmode="numeric" pattern="[0-9]*" required>
        </div>
        <div class="input-group-seperator"></div>
        <div class="input-group flex-nowrap">
          <input type="text" class="form-control form-control--otp js-otp-input" inputmode="numeric" pattern="[0-9]*" required>
          <input type="text" class="form-control form-control--otp js-otp-input" inputmode="numeric" pattern="[0-9]*" required>
          <input type="text" class="form-control form-control--otp js-otp-input" inputmode="numeric" pattern="[0-9]*" required>
        </div>
      </div>
    </fieldset>
  </form>

That is all for the HTML

Step 2: Writing the CSS code and adding the Styling for our project

Go create a file named as style.css

And start writing the code

The first section of html, body is going to set the height and width of the HTML and body elements to 100% and is going to make them a flex container using display as flex. The flex container is centered both vertically and horizontally using the align items and justify content properties of flex box.

The second section of .container is going to the max width of the container element to 600px ( px means pixel which is a unit in CSS) and add some padding to it.

html, body {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  max-width: 600px;
  padding: 2rem;
}

Lets now add on some bootstrap

The .form-control–otp class is going to define the styling for the input fields used for entering the one time password or OTP. It is going to set the line height and height to give the inputs a certain height with spacing. It also set the font-size and font-weight for better visibility with text alignment to center. The padding-left and padding-right are set to give some padding inside the input fields.

Responsive Hamburger Menu Using HTML and CSS Only

There is also a media query which will only activate when screen min size will be 375px. The font size and height is increased for better readability on larger screens.

The .input-group-seperator class is going to define the styling of the separator between two sets of inputs. It set the width with height and background color, as well as the left and right margins to give it some spacing in left and right. The border-radius is also used to give it an rounded appearance.

/* Bootstrap Add-On (BEM-syntax)
_________________________________________ */

.form-control--otp {
  line-height: 2.5;
  height: 3.5rem;
    font-size: 1.5rem;
  font-weight: bold;
  text-align: center;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

@media ( min-width: 375px ) {
  .form-control--otp {
    line-height: 3;
    height: 4.5rem;
    font-size: 2rem;
    font-weight: bold;
    text-align: center;
    max-width: 3.5rem;
  }
}

.input-group-seperator {
  width: 2rem;
  margin-left: 0.75rem;
  margin-right: 0.75rem;
  height: 0.3rem;
  background: #ced4da;
  border-radius: 0.1rem;
}

That concludes the CSS

Step 3: Writing the JavaScript code and adding the Functionality to our project

Go create a file named as script.js

First some var variables are declared on top of the code after that a function is written called otp and inside this also there are two var variable defined as inputs and callback, inside this function there is a another function called init

var BACKSPACE_KEY = 8;
var ENTER_KEY = 13;
var TAB_KEY = 9;
var LEFT_KEY = 37;
var RIGHT_KEY = 39;
var ZERO_KEY = 48;
var NINE_KEY = 57;

function otp(elementId) {
  var inputs = document.querySelectorAll('.js-otp-input');
  var callback = null;

  function init(completeCallback) {
    callback = completeCallback;
    for (i = 0; i < inputs.length; i++) {
      registerEvents(i, inputs[i]);
    }
  }

Now lets add more functions

There is a function called onpaste which is going to handle the input fields when the user will paste the otp instead of writing it. 3 event listener are also added in the code below which are as inputpaste , keydown. On the last part of the code there is a statement of If and else is written.

Also, Inside the onpaste function a for loop if there.

The inputpaste , keydown event listener are inside a function called registerEvents

A function named as destroy is also there which has a for loop.

function destroy() {
    for (i = 0; i < inputs.length; i++) {
      registerEvents(i, inputs[i]);
    }
  }

  function registerEvents(index, element) {
    element.addEventListener("input", function(ev) {
      onInput(index, ev);
    });
    element.addEventListener("paste", function(ev) {
      onPaste(index, ev);
    });
    element.addEventListener("keydown", function(ev) {
      onKeyDown(index, ev);
    });
  }

  function onPaste(index, ev) {
    ev.preventDefault();
    var curIndex = index;
    var clipboardData = ev.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData("Text");
    for (i = 0; i < pastedData.length; i++) {
      if (i < inputs.length) {
        if (!isDigit(pastedData[i])) break;
        inputs[curIndex].value = pastedData[i];
        curIndex++;
      }
    }
    if (curIndex == inputs.length) {
      inputs[curIndex - 1].focus();
      callback(retrieveOTP());
    } else {
      inputs[curIndex].focus();
    }
  }

Next add more functions

A function named as onKeyDown is created here inside which there is a var variable named as key is also declared.

There are total 5 if condition in this part of code not only that, but inside the the 3rd if condition there is an if else condition too.

function onKeyDown(index, ev) {
   var key = ev.keyCode || ev.which;
   if (key == LEFT_KEY && index > 0) {
     ev.preventDefault(); // prevent cursor to move before digit in input
     inputs[index - 1].focus();
   }
   if (key == RIGHT_KEY && index + 1 < inputs.length) {
     ev.preventDefault();
     inputs[index + 1].focus();
   }
   if (key == BACKSPACE_KEY && index > 0) {
     if (inputs[index].value == "") {
       // Empty and focus previous input and current input is empty
       inputs[index - 1].value = "";
       inputs[index - 1].focus();
     } else {
       inputs[index].value = "";
     }
   }
   if (key == ENTER_KEY) {
     // force submit if enter is pressed
     ev.preventDefault();
     if (isOTPComplete()) {
       callback(retrieveOTP());
     }
   }
   if (key == TAB_KEY && index == inputs.length - 1) {
     // force submit if tab pressed on last input
     ev.preventDefault();
     if (isOTPComplete()) {
       callback(retrieveOTP());
     }
   }
 }

Next, there total three functions these all will help our input field to function better.

First there is an function declared named as onInput Inside of this function two var variables are created and there are some if else statements inside the for loop.

Then we will declare another function named as retrieveotp inside this function 1 var variable is declared and another function is setup along with a for loop.

then there are another function declared named as isOTPComplete and isDigit inside the isOTPComplete function there is a while loop.

  function onInput(index, ev) {
    var value = ev.data || ev.target.value;
    var curIndex = index;
    for (i = 0; i < value.length; i++) {
      if (i < inputs.length) {
        if (!isDigit(value[i])) {
          inputs[curIndex].value = "";
          break;
        }
        inputs[curIndex++].value = value[i];
        if (curIndex == inputs.length) {
          if(isOTPComplete()) {
            callback(retrieveOTP());
          }
        } else {
          inputs[curIndex].focus();
        }
      }
    }
  }

  function retrieveOTP() {
    var otp = "";
    for (i = 0; i < inputs.length; i++) {
      otp += inputs[i].value;
    }
    return otp;
  }

  function isDigit(d) {
    return d >= "0" && d <= "9";
  }

  function isOTPComplete() {
    var isComplete = true;
    var i = 0;
    while (i < inputs.length && isComplete) {
      if (inputs[i].value == "") {
        isComplete = false;
      }
      i++;
    }
    return isComplete;
  }

  return {
    init: init
  };
}

After this

There is an variable declared with name as optModule

var otpModule = otp("otp-inputs");
otpModule.init(function(passcode) {});

That will make our OTP inputs.

Lets look at the video again

Live Preview Of Otp Input Field Using HTML and CSS:

Thank you so much

How is this OTP input field created?

This is created front-end languages using just HTML, CSS, and JavaScript

OTP input field Is responsive?

Yes, This is responsive which means it can run on any device like mobile, desktop, laptop, or even tablet.

Is JavaScript necessary for making OTP input field?

Yes, Without JavaScript it will be little hard for you to create this as this has a lots of functions to perform like DOM manipulation, etc.

Will this even ensure that the OTP is correct or not?

This currently has no features about ensuring that the OTP entered is correct or not but you can customize it in your way.

Leave a Comment