Achaius
Achaius

Reputation: 6124

How to capture user input into a field one letter at a time

We would like to mimic taking user input one letter at a time (intended for children). Assuming they are going to type "hello" we would want to capture all the letters separately. (e.g. you will show something like 5 underscores to show that they have to provide 5 inputs). Assuming they enter h e l d (i.e. the last letter is a mistake) they could press the Backspace button to erase it.

We tried using input type text field, but couldn't get the desired output. How can we achieve this either via HTML or jQuery?

Upvotes: 1

Views: 987

Answers (1)

egyedg
egyedg

Reputation: 724

My approach would be to catch the keydown event, and then do the validation, and in case of success display the correct letter instead of the underscore.

A simplified scheme:

HTML (needs some css to format):

...
 <ul id="wordToEnter">
   <li>_</li>
   ...
   <li>_</li>
 </ul>
...

- or can be generated programatically, the point is to have one li element for each letter

Javascript (with JQuery) :

var currentLetter = 1;
var expectedWord = "HELLO"; // this can be obtained dynamically

$(window).keydown(function (event) { 
  var keyCode = String.fromCharCode(event.keyCode);
  if (keyCode == expectedWord.charAt(currentLetter - 1)) {
     changeUnderscoreToLetter(keyCode);
  }
});

function changeUnderScoreToLetter(letter) {
   $("#wordToEnter>li:nth-child(" + currentLetter + ")").text(letter);
   currentLetter++;
   if (currentLetter > $("#wordToEnter li").length)
      alert("Word enetered");
}
  • could contain errors (didn't tested it) and can be optimized

Hope it helps.

Upvotes: 1

Related Questions