So here in my form. There are two button which is submit and reset button. If the user answer the question correctly, the score will increasing but if not the scoring will reducing. So when I try to reset the score to 0, the users’ score will deducting. I have tried many possible answer but its not working.
<body>
<form action="" class="from" id="form">
<h3 class="score" id="score">
Score : 0
</h3>
<h1 class="question" id="question">1 + 1</h1>
<input type="text" class="input" id="input"
placeholder="Enter Your Answer" autofocus autocomplete="off"
>
<button class="button">Submit</button>
<button class="reset" id="resetScore">Reset</button>
</form>
<script>
const a = Math.round(Math.random() * 5);
const b = Math.round(Math.random() * 5);
// question declared
const questionDisp = document.getElementById("question");
// form declared
const form = document.getElementById("form");
// input declared
const input = document.getElementById("input");
// score declared
const score1 = document.getElementById("score");
// reset declared
const reset = document.getElementById("resetScore");
let score = JSON.parse(sessionStorage.getItem("score"));//JSON.parse to convert the string to number
if (!score){
score = 0;
}
score1.innerText = `Score : ${score}`;
questionDisp.innerText = `What is ${a} + ${b} = `;
// answer for question declared
const answer = a + b;
form.addEventListener("submit", ()=>{
const userAns = +input.value //plus to convert string to number
if (userAns === answer ){
score++;
ScoreUpdate()
} else {
score--;
ScoreUpdate()
showAlert()
}
});
document.getElementById("resetScore").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("resetScore").innerHTML = "YOU CLICKED ME!";
}
function ScoreUpdate(){
sessionStorage.setItem("score", JSON.stringify(score))
}
function showAlert() {
alert ("WRONG ANSWER");
}
function deleteScore(){
sessionStorage.clear();
}
</script>
</body>
</html>