The button is converting my text to a string instead of the integer format that I require

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.

Answer №1

Give this a shot:

scoreTotal.textContent = parseInt(scoreTotal.textContent) + score;

Looks like you're unintentionally concatenating strings instead of adding numbers. Make sure to use parseInt() if you want numerical addition, as .textContent returns a string.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

Angular 2 repeatedly pushes elements into an array during ngDoCheck

I need assistance with updating my 'filelistArray' array. It is currently being populated with duplicate items whenever content is available in the 'this.uploadCopy.queue' array, which happens multiple times. However, I want to update ...

Adjust the size of the image within a designated container to decrease its proportions when there is an excess of text present

I am working on a project where I need to resize an image based on the available space within its container. When there is text in the description, the image should adjust its size accordingly without pushing the text upwards. I am using React for this pro ...

Positioning the filters in jQuery Datatables

I'm currently working with jQuery datatables and I'm attempting to align the filter/search box on the same row as the header of the container holding the datatable. Attached is a screenshot for reference: https://i.stack.imgur.com/nzbIl.png He ...

When should one close a custom-built jQuery dropdown menu?

I created a simple dropdown using a <div> (parent), <span> (current selection), and <ul> (options) which is functioning properly. Now, I'm looking to enhance it by implementing a feature that allows the dropdown to close when the use ...

React: State does not properly update following AJAX request

I'm currently facing a challenge in my React project where I need to make two AJAX calls and update the UI based on the data received. Below is the implementation of my render method: render() { if (this.state.examsLoaded) { return ( ...

Attempting to retrieve nested data, only to be met with an undefined response

I've been attempting to retrieve specific information by iterating through the SearchResult object like so: for (let productKey in SearchResult) { if (SearchResult.hasOwnProperty(productKey)) { products.push({ name ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Positioning pop-up windows using Javascript and CSS techniques

In my web application, there is a search field that allows users to enter tags for searching. The window should pop up directly below the search field as shown in this image: Image I am trying to figure out how the window positioning is actually d ...

Unchecked checkbox displays as checked in UI

I am facing an issue with checking checkboxes using JavaScript. Even though the checkbox appears to be checked in the program, it does not reflect the updates on the user interface. If anyone has a solution for this, please share. <!DOCTYPE html> ...

Algorithm that continuously increases a given date by 3 months until it surpasses or matches the specified creation date

I am currently working with QuickBase, a platform that involves HTML. My goal is to develop a code that can take a [fixed date] (always in the past) and increment it by 3 months until the MM/YYYY exceeds or equals the MM/YYYY of the [creation date]. Once t ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Is there a way to download a file using an ajax request?

We are faced with a particular scenario in our application where: Client sends a request Server processes the request and generates a file Server sends the file back as a response Client's browser prompts a dialog for downloading the file Our appli ...

Error in Mathquill: Unable to access the 'prototype' property because it is undefined

I'm currently in the process of integrating MathQuill into a project I'm developing. After installing the package through NPM (npm install mathquill), I included the following <script> tags in the <head>: <script src="../node_ ...

Is there a way to initiate the server only after webpack has finished bundling all of the bundles

"scripts": { "start": "node server.js", "build": "webpack" }, Is there a way to execute both npm run build and npm start with a single command? "scripts": { "start": " ...

Invoking numerous functions through the (click)= event

When it comes to removing a user from my site, I find myself having to execute multiple database queries to delete the user's ID across approximately 10 different tables. Currently, I am resorting to what I consider a messy workaround where I have mu ...

Streaming videos on Xbox One is not supported while in developer mode

Currently, I am facing a challenge with my UWP app that runs a web application made for Xbox One. There is a bug that only appears after approximately 4 hours of streaming video content, causing the app to freeze unexpectedly on the machine. The issue lie ...

Having trouble with HTML - JavaScript function not processing responseText?

On my website, there is a button array that displays the position of a robot by reading a text file using a php/ajax combo. The script initially sets all buttons to the same color and changes the color of the button to represent the robot's position. ...

Reorder the Polymer dom-repeat element following a modification in the child component's value

My Polymer dom-repeat list is working fine on the initial value sorting for the children. However, when I update a value within a child element, the sort order of the list does not reflect the changes. What is the best way to achieve this? <body> ...