Hello everyone,
I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below.
(html)
<div class="action">
<button id="start" onclick="start()">Start</button>
// The Stay function is yet to be implemented
<button id="stay">Stay</button>
</div>
<div class="announce" id="afterStart">
<p id="hit"></p>
(javascript)
function start() {
let score = Math.floor(Math.random() * 11 + 1);
let scoreTotal = document.getElementById("score-total");
scoreTotal.textContent = `Your score: ${score}`
The initial part of the code retrieves the button ID of the Start button. It then displays the text "Your Score" followed by a random number ranging from 1 to 11.
let proceed = document.getElementById("hit");
if (score < 21) {
proceed.textContent = "Do you wish to use another card?"
let hitButton = document.createElement("button");
hitButton.innerHTML = "Hit";
This segment selects the ID of the second div in the HTML and generates a new button displaying the text "Hit." Upon clicking "Hit," it executes the following function:
hitButton.onclick = function () {
let score = Math.floor(Math.random() * 11 + 1);
scoreTotal.textContent += score;
}
However, the issue lies here. If I click "Start" and receive the random number 3, it will show:
Your score: 3
But when hitting "Hit" and getting, say, 11, it concatenates the numbers instead of adding them together. This results in 311 instead of 14. Despite trying various approaches like using + or parseInt, nothing seems to resolve the problem. Here's the remainder of my code.
let myButton = document.getElementById("afterStart")
myButton.appendChild(hitButton);
document.getElementById("start").onclick = null;
This simply adds the Hit button beneath some text, and upon pressing "Start," I choose to deactivate the button.
} else if (score === 21) {
proceed.textContent = "You won!"
} else {
proceed.textContent = "You lose!"
}
For those finding all these spaces confusing, here's my full function.
In essence, my query boils down to this:
How do I ensure that my "Hit" button increments the total score as an integer rather than a string?
This marks my second project attempt: Blackjack! While my first project on unit conversion went smoothly, I'm facing challenges with this one. I'm determined not to rely on tutorials, having spent months in tutorial limbo.