Rory L.
Rory L.

Reputation: 458

js button not updating innerhtml

I have looked at numerous questions already on here and I haven't been able to find a similar problem. I am trying to give a button a function that updates a variable (specifically a number, i.e. - button press >> 0 becomes 1) and write it to the innerHTML of a div. It updates in an alert, but it doesn't update the innerHTML.

var example = 0;
var exampleDiv = document.getElementById('exampleDiv');

function buyExample() {
  example += 1;
}

exampleDiv.innerHTML = 'You have ' + example + ' examples.';

The number displayed on the webpage is 0.

Upvotes: 2

Views: 621

Answers (4)

Maxim Kuzmin
Maxim Kuzmin

Reputation: 2614

Your code is not working properly since exampleDiv.innerHTML is set only once. You have to move it to the function.

var example = 0;
var exampleDiv = document.getElementById('exampleDiv');
render();

function buyExample() {
  example += 1;
  render();
}

function render() {
  exampleDiv.innerHTML = 'You have ' + example + ' examples.';
}
<button id="button" onclick="buyExample()">Button</button>

<div id="exampleDiv"></div>

Upvotes: 1

Will
Will

Reputation: 3241

You have to move the statement that updates the DOM into the function that runs each time the button is clicked. The way you have it, the innerHTML is set once when the page loads and the variable example gets updated on each click, but you never set the value of example to the page again.

var example = 0;
var exampleDiv = document.getElementById('exampleDiv');

function buyExample() {
  example += 1;
  exampleDiv.innerHTML = 'You have ' + example + ' examples.';
}
<div id="exampleDiv">You have 0 examples.</div>
<button onclick="buyExample()">buy</button>

Upvotes: 0

user94559
user94559

Reputation: 60143

Working code based on my comment above:

var example = 0;
var exampleDiv = document.getElementById('exampleDiv');

function buyExample() {
  example += 1;
  exampleDiv.innerHTML = 'You have ' + example + ' example' + (example !== 1 ? 's' : '') + '.';
}

document.getElementById("incrementButton").onclick = buyExample;
<button id="incrementButton">Click me</button>

<div id="exampleDiv">You have 0 examples.</div>

Upvotes: 0

Michael Conard
Michael Conard

Reputation: 719

From the context you've given, your statement:

exampleDiv.innerHTML = 'You have ' + example + ' examples.';

Will only run once when the Javascript initializes, at which point the example variable is still set to 0. If you want the div to update every time you use the button, it needs to be included in the buyExample() method as well.

function buyExample() {
    example += 1;
    exampleDiv.innerHTML = 'You have ' + example + ' examples.';
}

Upvotes: 0

Related Questions