Im unable to capture the esc keypress / cancel button press during the prompt window execution in Javascript.
Because of this, if I do esc / cancel on prompt, its incrementing 1st Value in the array. (answers[0] is getting incremented everytym).
answers: new Array(5).fill(0),
registerNewAnswer() {
let userAnswer = prompt(
`${this.question}\n${this.options.join("\n")}\n(Write option number)`
);
document.onkeydown = function(e) {
console.log(key); /* This statement isn't getting executed on any key press.
Esc key press / Cancel button press should exit the base function (registerNewAnswer) from here */
}
typeof userAnswer === "number" &&
userAnswer <= this.answers.length &&
this.answers[userAnswer] ;
this.displayResult();
this.displayResult("string");
},
CodePudding user response:
The document.onkeydown
wouldnt work on the prompt. It works when you press key on your HTML page.
Remove the preceding
from the prompt
. You can detect the escape/cancel as the prompt will return null
in userAnswer
. The preceding
converts the null
to zero.
CodePudding user response:
I had removed the number conversion in assigning place, So I can capture the null value. Number conversion is done atlast.
PFB revised code.
let userAnswer = prompt(
`${this.question}\n${this.options.join("\n")}\n(Write option number)`
);
if (!userAnswer || userAnswer.trim() === "") return; // 1st to capture esc key / cancel button & 2nd to capture single space input.
userAnswer = userAnswer;
if (isNaN(userAnswer)) return;
typeof userAnswer === "number" &&
userAnswer < this.options.length &&
this.answers[userAnswer] ;
this.displayResult();
this.displayResult("string");