Is it not possible to update the innerHTML stored in a variable in real-time?

I am attempting to link a div's text with a variable that changes its value based on different button clicks (using plain JavaScript), but I am struggling to update the inner HTML dynamically. It only displays the initial value set on page load. What am I missing? As a JavaScript student, any help is appreciated.

var counter1=0;
var counter2=0;
var counter3=0;

var countertotal=counter1+counter2+counter3;
document.getElementById("text").innerHTML= "Total" + "&nbsp" + parseInt(countertotal);

function count1() {
document.getElementById("button1").innerHTML =parseInt(counter1);
counter1++;
}
function count2() {
document.getElementById("button2").innerHTML =parseInt(counter2);
counter2++;
}
function count3() {
document.getElementById("button3").innerHTML =parseInt(counter3);
counter3++;
}
<html>
<body>

<div id='text' style="font-size:50px"></div>
<button style= "width:400px; height:150px; font-size:100px;
 display:block" id="button1" onclick="count1()"></button>

<button style="width:400px;height:150px; font-size:100px;
 display:block" id="button2" onclick="count2()"></button>

<button style="width:400px;height:150px;font-size:100px;display:block" id="button3" onclick="count3()"></button>
</body>
</html> 

Answer №1

Make sure to update the total counter each time you click a button and then update the innerHTML of the counter total. It's important to update the counter for every button, not just one.

For instance, in the count1 function:

function count1() {
   document.getElementById("button1").innerHTML =parseInt(counter1);
   counter1++;
   countertotal++;
   document.getElementById("text").innerHTML =  "Total" + " " + 
   parseInt(countertotal);
}

Additionally, the value of countertotal doesn't update automatically because JavaScript runs code sequentially from top to bottom and passes values by value. To learn more about this, you can refer to the following link: value vs reference

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

Exploring Jinja: Navigating through nested JSON structures

I am currently delving into Jinja in order to construct a basic website. How can I retrieve values from nested JSON using Jinja syntax? For instance: How do I isolate the "Education" key from the JSON snippet below to fill in the HTML snippet? ...

What is the best way to transform a string representation of data into an array and then showcase it in

After importing CSV data and converting it into the variable stringData, I am facing an issue when trying to display this data in a React table. Although I have attempted to use the map function to separate the headers and map to <th>, displaying t ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Issue with absolute positioning occurs when the screen resolution or window size is altered, causing the feature to

Take a look at the code snippet below: <div style="position: relative;"> <div style="position: absolute; left: 10px; top: 18px;"> <img id="ImgTachoMetre" src="/Images/u174_normal.png"> </div> </div> I have wr ...

Tips on utilizing variables instead of static values when calling objects in JavaScript

How can I make something like this work? I tried putting the variable in [], but it didn't work. Can someone please help me out with this? Thank you. const obj = { car : "a" , bus: "b" }; const x = "car" ; ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

You need to click the form submit image twice in order to make it work

Struggling to get a standard opt-in form to work with an image submit button. The script works fine with a regular submit button, but the image button requires two clicks initially and then one click after unless the page is refreshed. I believe there mig ...

Toggle the jQuery class off when a different element is chosen

I've created a function that toggles a class to change the style of an element when it is selected. However, I'm facing an issue where the new style remains even when another element is selected. Is there a way to make the styling revert back to ...

Locate the data attribute and store it in the database using an ajax request

I am in need of a proper script to insert a data attribute into the database upon clicking using ajax. HTML: <li><a data-cat="random name">Button</a></li> jQuery: $('li a').click(function() { $(this).data('cat&a ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

Guide to swapping images on button click in HTML with dynamically changing image URLs retrieved from the server

I am a beginner in client-side scripting and new to Stack Overflow. I am looking for guidance on how to change an image within a div element upon clicking a button or anchor tag. Here is the code snippet I have written to achieve this: $scope.captchaCha ...

Utilizing AngularJS to target DOM elements within an ng-repeat loop

I currently have my ng-repeat set up within a div tag: <div ng-repeat="x in names"> <h1>{{x.product}}</h1> <h2>{{x.brand}}</h2> <h3>{{x.description}}</h3& ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

I am looking to configure a specific MUI dropdown to appear below a particular field

In my scenario, when I click on the select dropdown and a popup appears above the field, I would like it to open below that specific area. The desired behavior can be observed in the code sandbox link provided. I need to configure it to start from below th ...

Utilizing Bootstrap's styling features for iOS browser: customizing borders and text in HTML

On the iPhone browser, I am encountering an issue with my code. Specifically, the text disappears and the div border or shadow changes, but when I test it on Safari browser, everything looks fine. The developer version of the website can be found at: Conta ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

What could be the reason that Vue is not evaluating anything when the directive @click is specified as "true && method"?

Consider the following scenario: LandingPage.vue <template> <button @click="handleClick">Click Me</button> </template> <script> export default { methods: { handleClick() { this.$emit("click"); } } }; < ...