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 sep开发者_如何学运维arately. (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?
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.
精彩评论