How to count the number of times a button is clicked?

I tried to write a script that increments a variable value, every time a button is clicked.

  <script type="text/javascript">

  // if the count variable is undefined, set its value to zero
  if(! count) {
  var count = 0;
  }

  // function to increment value of count variable
  incrementCount() {
    count++;
  }
  </script>

  <!-- button to call incrementCount() function, on click -->
  <form>
    <input type="button" value="Count"  onclick="incrementCount()">
  </form>
  <br />

  <script type="text/javascript">
  // output count variable
  document.write(count);
   </script> 

Unfortunately the script is not working. Could you please tell me why?

Thanks!

This search shows many examples https://www.google.com/search?q=javascript+count+number+of+clicks&ie=UTF-8&oe=UTF-8&hl=en&client=safari

Hi there Fergal,

There were a number of errors in the script you posted.

The main two were that this:

incrementCount() {
  count++;
}

was missing the key word “function”. It should be:

function incrementCount() {
  count++;
}

Also, you are not updating the display after the button was pressed.

Here’s a working script for you to play around with:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Increment count when button is clicked</title>
  </head>

  <body>
    <input type="button" value="Count" id="countButton" />

    <p>The button was pressed <span id="displayCount">0</span> times.</p>

    <script type="text/javascript">
      var count = 0;
      var button = document.getElementById("countButton");
      var display = document.getElementById("displayCount");

      button.onclick = function(){
        count++;
        display.innerHTML = count;
      }
    </script>
  </body>
</html>

Hopefully it should be clear enough what’s going on, but if you have any questions, don’t hesitate to ask.

Thanks Eric, I had already been through some of those links, but am new to JavaScript and couldn’t get them to work.

Thanks ever so much Pullo, I really appreciate you taking the time to do that and I will go through it in detail tomorrow.

As you may know it’s your “fault” I’m here :slight_smile:

Me and my big mouth … :slight_smile:

Seriously though, that’s fine!
JavaScript really is the way to go for this functionality and I’m more than happy to explain things to you at whatever level you need.