HomeJavascriptOTP Input Field | Javascript

OTP Input Field | Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, you will learn how to create an OTP input field. To build this project we need HTML, CSS and JavaScript.
This is an intermediate-level JavaScript project. Even beginners can give it a try, as I have explained each step with the help of comments.

If you are looking for more such projects to improve your JavaScript skills, you can check out this playlist here. This playlist contains more than 100 projects. The difficulty level of this project varies from easy to quite complex. Hence these projects are suitable for all kinds of JavaScript learners.

Video Tutorial:

If you are interested to learn by watching a video tutorial instead of reading this blog post, you can check out the video down below. Also, subscribe to my YouTube channel Where are post new tips tricks and tutorials regularly.

Project Folder Structure:

Before we start coding, let us take a look at the project folder structure. We create a project folder called the OTP input field. Within this folder, we have three files. These files are index.HTML,style.CSS and script.js The first file is the HTML document, the second file is the stylesheet, and finally, we have the script file.

HTML:

We begin with HTML code. Copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>OTP Input</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="inputfield">
        <input type="number" maxlength="1" class="input" disabled />
        <input type="number" maxlength="1" class="input" disabled />
        <input type="number" maxlength="1" class="input" disabled />
        <input type="number" maxlength="1" class="input" disabled />
      </div>
      <button class="hide" id="submit" onclick="validateOTP()">Submit</button>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style this app using CSS. For this, once again copy the code provided to you below and paste it into a stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  height: 100vh;
  background: linear-gradient(#fcf1e2 50%, #ffb800 50%);
}
.container {
  width: 28em;
  background-color: #ffffff;
  padding: 8em 2em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  border-radius: 0.8em;
  box-shadow: 0 45px 60px rgba(30, 22, 1, 0.3);
}
.inputfield {
  width: 100%;
  display: flex;
  justify-content: space-around;
}
.input {
  height: 3em;
  width: 3em;
  border: 2px solid #dad9df;
  outline: none;
  text-align: center;
  font-size: 1.5em;
  border-radius: 0.3em;
  background-color: #ffffff;
  outline: none;
  /*Hide number field arrows*/
  -moz-appearance: textfield;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
#submit {
  background-color: #ffb800;
  border: none;
  outline: none;
  font-size: 1.2em;
  padding: 0.8em 2em;
  color: #000000;
  border-radius: 2em;
  margin: 1em auto 0 auto;
  cursor: pointer;
}
.show {
  display: block;
}
.hide {
  display: none;
}
.input:disabled {
  color: #89888b;
}
.input:focus {
  border: 3px solid #ffb800;
}

Javascript:

Finally, we implement the functionality using JavaScript. I have explained each step with help of comments.

//Initial references
const input = document.querySelectorAll(".input");
const inputField = document.querySelector(".inputfield");
const submitButton = document.getElementById("submit");
let inputCount = 0,
  finalInput = "";

//Update input
const updateInputConfig = (element, disabledStatus) => {
  element.disabled = disabledStatus;
  if (!disabledStatus) {
    element.focus();
  } else {
    element.blur();
  }
};

input.forEach((element) => {
  element.addEventListener("keyup", (e) => {
    e.target.value = e.target.value.replace(/[^0-9]/g, "");
    let { value } = e.target;

    if (value.length == 1) {
      updateInputConfig(e.target, true);
      if (inputCount <= 3 && e.key != "Backspace") {
        finalInput += value;
        if (inputCount < 3) {
          updateInputConfig(e.target.nextElementSibling, false);
        }
      }
      inputCount += 1;
    } else if (value.length == 0 && e.key == "Backspace") {
      finalInput = finalInput.substring(0, finalInput.length - 1);
      if (inputCount == 0) {
        updateInputConfig(e.target, false);
        return false;
      }
      updateInputConfig(e.target, true);
      e.target.previousElementSibling.value = "";
      updateInputConfig(e.target.previousElementSibling, false);
      inputCount -= 1;
    } else if (value.length > 1) {
      e.target.value = value.split("")[0];
    }
    submitButton.classList.add("hide");
  });
});

window.addEventListener("keyup", (e) => {
  if (inputCount > 3) {
    submitButton.classList.remove("hide");
    submitButton.classList.add("show");
    if (e.key == "Backspace") {
      finalInput = finalInput.substring(0, finalInput.length - 1);
      updateInputConfig(inputField.lastElementChild, false);
      inputField.lastElementChild.value = "";
      inputCount -= 1;
      submitButton.classList.add("hide");
    }
  }
});

const validateOTP = () => {
  alert("Success");
};

//Start
const startInput = () => {
  inputCount = 0;
  finalInput = "";
  input.forEach((element) => {
    element.value = "";
  });
  updateInputConfig(inputField.firstElementChild, false);
};

window.onload = startInput();

That’s it for this tutorial. You can now go ahead and customise this code the way you want.
If you face any difficulties while creating the code, you can download the source code by clicking on the download button below. Also, if you have any queries, suggestions or feedback you can comment on them below.
Happy Coding!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

16 + 10 =

Most Popular