Start learning free

LESSON 153 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Two-Factor Code Input in JavaScript

Practice

A sign-in code often comes as six separate fields, one digit each. To feel like one field, they move the focus for the visitor: a typed digit jumps to the next field, Backspace in an empty field jumps back, and a pasted code fills all six at once.

In React, you reach a real input element with a ref, and its focus() method puts the cursor in it. For example, a button that moves the cursor into a search field:

const box = useRef(null);
// …
<input ref={box} aria-label="Search" />
<button onClick={() => box.current.focus()}>Search</button>

Keys arrive in onKeyDown, where event.key is the key's name, like "Backspace". A paste arrives in onPaste: event.clipboardData.getData("text") is the pasted text, and event.preventDefault() stops the browser from pasting it into the field itself. The starting code keeps the six digits in digits and the six inputs, in order, in inputs.current.

The check does this, and your page must answer:

> type "4" into "Digit 1"        →  Digit 1: "4", focus moves to Digit 2
> press 2                        →  Digit 2: "2", focus moves to Digit 3
> press Backspace                →  focus moves back to Digit 2
> press Backspace                →  Digit 2: ""
> type "23456" into "Digit 2"    →  Digits 2 to 6 filled, focus on Digit 6
                                    status: Checking 423456
> paste "123456" into "Digit 1"  →  1 2 3 4 5 6, focus on Digit 6
                                    status: Checking 123456

Your task: move the focus to the next field after a digit, write handleKeyDown to go back on Backspace in an empty field, and write handlePaste to spread a pasted code over the six fields; then connect both handlers to every input.


Assignment
Follow the Coding Tutorial to make the six code fields move the focus when the visitor types, presses Backspace and pastes.


Hint
Field index is inputs.current[index], so the next one is at index + 1 and the one before at index - 1. Digit 1 has no field before it, and Digit 6 has none after it.


STEP 1 OF 11
    Ctrl + Enter to check

    Fe Two Factor Input in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free