substract 7 every time (starting number is 100), the first answer will be 93, i dont want user to move on until he gets the first answer right
let answerInput = document.getElementById("inpu");
let checkButton = document.getElementById("send");
let answers = [];
for(let i = 100; i>2;){
i -= 7;
answers.push(i);// [93, 86,...]
}
checkButton.onclick = function(){
//my struggle here
if(isNaN(answerInput.value) === true){
answer.value = "";
answer.placeholder = "only numbers are allowed";
}
}
CodePudding user response:
There is no need to store the numbers in an array, seen as the next number is always 7 from the last, just keep a counter for the number. And then just compare this to the input - 7;
eg.
const span = document.querySelector('span');
const input = document.querySelector('input');
const button = document.querySelector('button');
let number = 100;
const showNum = () => span.innerText = number;
showNum();
button.addEventListener('click', () => {
const want = number - 7;
if (Number(input.value) === want) {
if (want == 2) {
alert("Well done you..");
} else {
number -= 7;
showNum();
}
}
});
Subtract 7 from <span></span> = <input type="number" value="100"/><button>Try</button>
CodePudding user response:
Solution:
let answerInput = document.getElementById("inpu");
let checkButton = document.getElementById("send");
let answers = [];
for (let i = 100; i > 2; ) {
i -= 7;
answers.push(i); // [93, 86,...]
}
checkButton.onclick = function () {
if (isNaN(answerInput.value) === true) {
answer.value = "";
answer.placeholder = "only numbers are allowed";
}
// check if answer correct, `!=` compare with type coercion
else if (answerInput.value != answers[0]) {
answer.placeholder = "try again"
}
else {
answers.shift(); // remove first array element
answer.placeholder = "correct!"
}
};
<!DOCTYPE html>
<html>
<head></head>
<body>
<!--
You can use type="number" to auto-avoid letters in field:
<input id=inpu type="number" />
-->
<input id=inpu />
<input disabled id=answer />
<button id=send>Send</button>
</body>
</html>