Manually implement js SMS verification code input box

Manually implement js SMS verification code input box

Preface

This article records a common SMS verification code input component for the front end that I manually implemented, and the process of gradual optimization from demand to implementation.

text

1. Demand Analysis

First, let’s take a look at the renderings.

First, when the page is loaded, the input box gets the focus. When the user enters a number, the focus automatically jumps to the second box. When all four boxes are entered, the submission request is simulated. Here, a pop-up box prompt is used to output the input verification code content. Requirements outside the main process: Only numbers can be entered in the input box, not letters. If a non-numeric type is forced to be entered, the verification code entered when the withdrawal key is pressed will be cleared and the current focus will jump to the first input box.

2. Complete code implementation.

The general idea is that when the page is loaded, add the autofocus attribute to the first input box to let it automatically get the focus, and then listen for keyboard click events. When the keyboard is pressed, determine whether the current key is a numeric key. If not, the current input box is set to empty and the focus is still in the current input box. If it is a number, determine whether there is a number in the previous input box. If not, jump the focus to the previous empty input box. Otherwise, enter the current input box and move the focus to the next input box. The focus is implemented through a pseudo-class of the input box. When the input length is 4, the numbers in each input box are concatenated into a string and prompted through a pop-up box.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .check-div {
        width: 400px;
        height: 600px;
        margin: 100px auto;
        border: 1px solid slategrey;
        text-align: center;
      }
      h1 {
        font-size: 24px;
      }
      .input-div {
        margin-top: 100px;
      }
      input {
        margin-left: 5px;
        text-align: center;
        width: 50px;
        height: 50px;
        border: none;
        /* Note that the default outer border attributes should be modified here, without border*/
        outline: 1px solid black;
      }
      input:focus {
        outline: 2px solid #3494fe;
      }
    </style>
  </head>
  <body>
    <div class="check-div">
      <h1>Please enter the verification code</h1>
      <div class="input-div">
        <input
          type="text"
          class="inputItem0"
          data-index="0"
          maxlength="1"
          autofocus
        />
        <input type="text" class="inputItem1" data-index="1" maxlength="1" />
        <input type="text" class="inputItem2" data-index="2" maxlength="1" />
        <input type="text" class="inputItem3" data-index="3" maxlength="1" />
      </div>
    </div>
    <script>
      var inputArr = document.getElementsByTagName("input");
      window.addEventListener("keyup", (e) => {
        let curIndex = e.target.getAttribute("data-index"); //Get the index of the current input //If you click BackSpace, delete all here if (e && e.keyCode == 8) {
          console.log(22222222222);
          for (let j = 0; j <= 3; j++) {
            inputArr[j].value = "";
            inputArr[0].focus();
          }
          return;
        }
        console.log("e.keyCode", e.keyCode);
        //If the input is not a numberif (!(e.keyCode >= 48 && e.keyCode <= 57)) {
          console.log(1111111111);
          inputArr[curIndex].value = "";
          return false;
        }
        //Traverse the array values ​​and concatenate them into a verification code string var str = "";
        for (let j = 0; j <= 3; j++) {
          console.log(inputArr[j].value);
          str += inputArr[j].value;
        }

        var nextIndex = Number(curIndex) + 1;
        //When judging that there are not enough four-digit verification codes if (curIndex < 3 && str.length < 4) {
          for (let i = 0; i <= curIndex; i++) {
            // Check if the previous one is empty or not, if yes, adjust the focus to the front and put the input back to the front, otherwise jump to the next one if (!inputArr[i].value) {
              inputArr[curIndex].blur();
              inputArr[i].value = inputArr[curIndex].value;
              var index = i + 1;
              inputArr[index].focus();
              inputArr[curIndex].value = "";
              return;
            } else {
              var nextIndex = Number(curIndex) + 1;
              inputArr[nextIndex].focus();
            }
          }
        } else {
          alert("The verification code submitted is " + str);
          //When a four-digit verification code is entered, a verification code request can be sent, etc.}
      });
    </script>
  </body>
</html>

Summarize

This is the end of this article about manually implementing the js SMS verification code input box. For more relevant js SMS verification code input box content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS validation input box (letters, numbers, symbols, Chinese)
  • JavaScript input box content format verification code

<<:  Zabbix monitoring solution - the latest official version 4.4 [recommended]

>>:  Introduction to the difference between on and where conditions in MySQL left join operation

Recommend

Summary of 10 must-see JavaScript interview questions (recommended)

1.This points to 1. Who calls whom? example: func...

How to use the MySQL authorization command grant

The examples in this article run on MySQL 5.0 and...

Detailed process of upgrading glibc dynamic library in centos 6.9

glibc is the libc library released by gnu, that i...

CentOS 8 officially released based on Red Hat Enterprise Linux 8

The CentOS Project, a 100% compatible rebuild of ...

MySQL slow query method and example

1. Introduction By enabling the slow query log, M...

Solution to the error when installing Docker on CentOS version

1. Version Information # cat /etc/system-release ...

A brief discussion on which fields in Mysql are suitable for indexing

Table of contents 1 The common rules for creating...

Example of how to change the line spacing of HTML table

When using HTML tables, we sometimes need to chan...

Practical record of Vue3 combined with TypeScript project development

Table of contents Overview 1. Compositon API 1. W...

Detailed explanation of custom instructions for Vue.js source code analysis

Preface In addition to the default built-in direc...

Table Tag (table) In-depth

<br />Table is a tag that has been used by e...

How to uninstall MySQL cleanly (tested and effective)

How to uninstall Mysql perfectly? Follow the step...

How to deal with time zone issues in Docker

background When I was using Docker these two days...