Text updating with variable changes

hello there, im new to this so sorry if this is a bad question.
i have four different buttons to answer and one of them is correct and increases the variable “score” by one, then in my html i have a line that says “your score is (score)” (this line is always on the page and is set at 0) how to i get the score to update when i push the button?

Hi and welcome, it’s difficult to help with this if we can’t see your code, but if any of your buttons causes a page reload, it’s impossible to save and update the score, unless you put it in the browser’s local storage or have some backend involved.
If that doesn’t answer your question, please post your HTML and JS code so we can see what you’re trying to do.

It also depends on how much you know about DOM manipulation. Do you already know how to insert or change text in the DOM?

its a math problem the correct button is -9

html x js

4(x+4)=1/2(10(x+5))

x=-4 x=7 x=3 x=-9

your score is

JAVASCRIPt

function myfunction2() {
x=2
if (x===2) {
alert(“sorry, that is wrong, your score has not been increased”)
}
}
function myfunction3() {
x=2
if (x===2) {
alert(“sorry, that is wrong, your score has not been increased”)
}
}
function myfunction4() {
x=4
score ++
if (x===4) {
alert(“yay! that is correct! your score has been updated!”)
}
}
function docWrite(score) {
document.write(score);
}

Howdy,

I am on mobile, so I can only help you a bit.

Make an array for the answers and scramble it, so you add dynamicity.

If you don’t need this, then create a function with argument “button” (something like function myFunction(button) {//your code here } ) and add onclick functions on every button, but like onclick=myFunction(0) and do myFunction(1), myFunction(2) and so on.

When you are inside the myFunction, you can add ifs, like if(button === 0) {} you add if you win or not. Make a div or p and add an id like:“scoreText” and initialize it with let scoreText = document.querySelector(“scoreText”);
scoreText = “Your score is 0”;

and then in the winning function you can do something like this:

function myFunction (button)
{
if(x===0)
{
//insert code
}
else if(x===1)
{
//insert code
}
else if(x===2)
{
//insert code
}
else if(x===3)
{
score++;
scoreText.innerHTML = "Your score is " + score;
}
}

Yes, I could have used a template literal on the string, but let’s make the things easier now.

I hope this helped you and tell me if there are problems.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.