themightyshrub
themightyshrub

Reputation: 35

Why isn't my variable going up by one?

I'm just starting out with code, and I'm trying to make a really simple web page button. All I really want to do is for the page to show a number, and then when you click a button, the number goes up by one.

I'm trying to do this by using JavaScript and having a variable set to one, and then a function that increases the variable that runs whenever the button is pressed. Logically, I think what I've done should work, but it doesn't, so I'm definitely missing something.

Code is as follows: HTML -

<script>
document.write(demo)
</script>
<button type="button" onclick="myFunction()">Increase Number</button>

and JavaScript -

var demo = 1;
function myFunction() {
demo++;
}

Is there something I need to put in the function to refresh the variable? At the moment, the page just loads as number 1 next to the button, nothing happens when I click.

Upvotes: 1

Views: 59

Answers (3)

Nick
Nick

Reputation: 16576

You just need to make sure you're writing the variable to the document after it is incremented.

var demo = 1;
function myFunction() {
  demo++;
  document.write(demo);
}

Upvotes: 0

Nisarg Shah
Nisarg Shah

Reputation: 14561

Yes, you need to print the variable every time you change it for the UI to be updated.

However, you should write it to a span or a div through innerText rather than using document.write to avoid overwriting the rest of HTML elements.

var demo = 1;

document.getElementById("demo").innerText = demo;

function myFunction() {
  demo++;
  document.getElementById("demo").innerText = demo;
}
<button type="button" onclick="myFunction()">Increase Number</button>
<span id="demo"></span>

Upvotes: 1

Ivar
Ivar

Reputation: 6848

The number does go up, but you already printed it by the time increment it. You can add a span tag to your HTML and use that to show the number in like this:

var demo = 1;
function myFunction() {
    demo++;
    document.getElementById('num').innerText = demo;
}
<span id="num">1</span>
<button type="button" onclick="myFunction()">Increase Number</button>

You use document.getElementById('num') to select the span tag and .innerText to set the number to it.

Upvotes: 3

Related Questions