I am having some problems implementing a click counter in Javascript. I have googled about it but I am not able to figure out the bug in my code.
In the following pen, I am using guesses variable as the counter. It seems every time I click on submit, my guesses variable gets reset to zero.
I am also pasting the code snippet here:
//let targetNumber = Math.floor(Math.random() * 10) + 1;
let targetNumber = 6;
var guesses = 0;
function init() {
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function() {
var guess = document.getElementsByName("number")[0]["value"];
guesses += 1;
guess = parseInt(guess);
check(guess);
});
}
function check(value) {
if (guesses < 5) {
if (value === targetNumber) {
showWin();
} else {
showError();
}
} else {
showLoss();
}
}
function showWin() {
var p = document.createElement("P");
var t = document.createTextNode("You Won!");
p.appendChild(t);
document.body.appendChild(p);
//document.getElementsByTagName("p")[0].innerHTML = "You Won!";
document.getElementsByTagName("form")[0].style.display = "none";
}
function showError() {
var p = document.createElement("P");
var t = document.createTextNode("Incorrect Guess! Try again.");
p.appendChild(t);
document.body.appendChild(p);
}
function showLoss() {
var p = document.createElement("P");
var t = document.createTextNode("You Lost!");
p.appendChild(t);
document.body.appendChild(p);
document.getElementsByTagName("form")[0].style.display = "none";
}
init();
<p>Guess a number between 1 and 10</p>
<form>
<input type="text" name="number">
<button>Submit</button>
</form>