Marc M.
Marc M.

Reputation: 39

How to update a displayed variable

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<script type="text/javascript">
var tic;
tic = 0;
</script>

<script type="text/javascript">
document.write(tic);
</script>




<script>
var ongngic;
ongngic = 1;
</script>

<button onclick="alert(tic=tic+ongngic);">Ice Cream</button>
</body>
</html>

I have displayed the variable "tic" with document.write. I'm not sure how to change it by clicking the id="b1" button. Can someone help me?

Upvotes: 1

Views: 41

Answers (2)

Kenath
Kenath

Reputation: 630

You need to bind the values to HTML like below.

<body>
  <div id="tic_div"></div>
    <button onclick="add()">Ice Cream</button>  
    <script type="text/javascript">
      var tic = 0;
      var ongngic = 1;

      document.getElementById("tic_div").innerHTML = tic;

      function add(){
        tic=tic+ongngic;
        document.getElementById("tic_div").innerHTML = tic;
      }
  </script>
</body>

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You need to update the variable as well as the DOM:

  • Do not use document.write().
  • Use a DOM Element and modify the .innerHTML.
  • Separate HTML and JavaScript.

var tic;
tic = 0;
var ongngic;
ongngic = 1;
document.getElementById("output").innerHTML = tic;
function perform() {
  tic= tic + ongngic;
  document.getElementById("output").innerHTML = tic;
}
<div id="output"></div>
<button onclick="perform();" type="button">Ice Cream</button>

Upvotes: 1

Related Questions