-1

Sorry, I'm totally new to javascript and need help with something you think is probably really stupid.

I'm trying to make it so that when you start the program, it prints 0, then when you press a button, it changes 0 to 1. This is what I have so far -

<!DOCTYPE html>
<html>

<p id="print"></p>

<script>

var x = 0

document.getElementById('button').onclick = function() {
x++;
};

document.getElementById("print").innerHTML = x;

</script>

<button id = "button">Change Variable x</button>


</body>
</html> 

Although, it doesn't print anything when I run the code. Please Help! (By the way, you are probably thinking that this is a stupid question.)

Thanks!

Nathan Chan
  • 303
  • 1
  • 13
  • 3
    Move the setter `document.getElementById("print").innerHTML = x;` inside event handler. [**Demo**](https://jsfiddle.net/tusharj/pq1pztk6/) – Tushar Dec 15 '16 at 03:29
  • 1
    Learn how to use your browser's developer tools. If you open the console you will see some errors. Please read [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/q/14028959/218196) – Felix Kling Dec 15 '16 at 03:38
  • Your button is after the script, it doesn't exist yet when you run `getElementById`. – Paul Dec 15 '16 at 03:40

3 Answers3

2

I hope this will work:

var x = 0

document.getElementById('button').onclick = function() {
   x++;
   document.getElementById("print").innerHTML = x;
};
Tushar
  • 78,625
  • 15
  • 134
  • 154
Akhter Al Amin
  • 722
  • 1
  • 9
  • 25
0

Not sure if this is what you are looking for, but all I did was make a function name and then whenever you click the button it adds 1 to the

<p id="print">hello</p>
<button id = "button" onclick="myFunction()">Change Variable x</button>
<script>

var x = 0

function myFunction(){
    document.getElementById('print').innerHTML = x+=1;
}
</script>
0

Here is a working snippet of what you are looking for, using javascript. When the user clicks the button, it changes the value to 1, and then when you click the alert button it alerts 1 instead of 0.

var changeMe = 0;
function changeVar() {
  changeMe = 1;
  }
function alertVar() {
  alert(changeMe);
  }
<button onclick="changeVar();">Change</button>
<button onclick="alertVar();">Alert</button>
Matthew Bergwall
  • 332
  • 1
  • 10