Skip to content
Advertisement

What’s the best way to code an input tag with certain locked characters?

Introduction

I would like to make an input of a fixed length that you can only fill some of the characters, for instance let’s say I have __llo w_rld! and i want the user to fill in the gaps, but not allow to modify the prefilled characters.

Ideas

I thought of using an input tag for each character and mark as disabled the prefilled ones, here is an example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
</head>
<body>
  <input size="1"></input>
  <input size="1"></input>
  <input size="1" value="l" disabled></input>
  <input size="1" value="l" disabled></input>
  <input size="1" value="o" disabled></input>
  &ensp;
  <input size="1" value="w" disabled></input>
  <input size="1"></input>
  <input size="1" value="r" disabled></input>
  <input size="1" value="l" disabled></input>
  <input size="1" value="d" disabled></input>
  <input size="1" value="!" disabled></input>
</body>
</html>

However this approach doesn’t allow the user to keep typing characters and jump from one input to the next one.

Is there any way of accomplishing this?

Advertisement

Answer

Using required and querySelector(':invalid') seems to work pretty well.

By the way, it’s not valid html to end <input> tags.

const container = document.getElementById("container");
container.addEventListener("input", ev => {
  container.querySelector("input:invalid")?.focus();
});
input {
  width: 1em;
}
<div id="container">
  <input required maxlength="1">
  <input required maxlength="1">
  <input value="l" disabled>
  <input value="l" disabled>
  <input value="o" disabled>
  &ensp;
  <input value="w" disabled>
  <input required maxlength="1">
  <input value="r" disabled>
  <input value="l" disabled>
  <input value="d" disabled>
  <input value="!" disabled>
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement