I can't resolved the problem due probably to jQuery. Here is my test.
I enter letters inside input. I expect a specific word. For each letter entered I compare its position and that le letter is this expected. If not ,I display an error. My code work only if I enter letters one by one each second.
If I write normally, in two seconds for example, each time the comparison stop and I get undefined value for a specific letter for different words.
I can assume one or multiple issue form one of them:
- It lacks a real time observation function ?
- Too much code to process in a short time ?
- the jquery library takes too much time to process the information ?
Of course, I can reduce my code, but is it really the problem ?
Or my code do to correspond that I expect .
if (keyval.length == 1 && e.key != "p") {
erase();
errorkey();
}
if (keyval.length == 2 && e.key != "o") {
erase();
errorkey();
}
if (keyval.length == 3 && e.key != "r") {
erase();
errorkey();
}
if (keyval.length == 4 && e.key != "t") {
erase();
errorkey();
}
if (keyval.length == 5 && e.key != "a") {
erase();
errorkey();
}
if (keyval.length == 6 && e.key != "l") {
erase();
errorkey();
}
if (keyval.length == 7 && e.key != "s") {
erase();
errorkey();
}
});
$(document).ready(function () {
$(document).on("focus", "#key", function () {
$("body").append('<input type="hidden" id="result" data-token="">');
});
function erase() {
$("#result").remove();
$("#key").val("");
}
$(document).on("keyup", "#key", function (e) {
let keyval = $("#key").val();
let resuval = $("#result").val();
let whichkey = e.which;
console.log(keyval.length + "<br/>" + whichkey);
let chains = whichkey.toString(16);
$("#result").val(function () {
return this.value + chains;
});
if (keyval == "portals") {
console.log("portals");
} else if (keyval != "portals" && keyval.length == 7) {
console.log("error");
}
function errorkey(whichkey) {
alert(
"You made a typing error. Please start again!" + whichkey
);
}
if (keyval.length == 1 && e.key != "p") {
erase();
errorkey();
}
if (keyval.length == 2 && e.key != "o") {
erase();
errorkey();
}
if (keyval.length == 3 && e.key != "r") {
erase();
errorkey();
}
if (keyval.length == 4 && e.key != "t") {
erase();
errorkey();
}
if (keyval.length == 5 && e.key != "a") {
erase();
errorkey();
}
if (keyval.length == 6 && e.key != "l") {
erase();
errorkey();
}
if (keyval.length == 7 && e.key != "s") {
erase();
errorkey();
}
});
$(document).on("focusout", "#key", function () {
erase();
});
});
body{background:#666;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="key">