GDesigns GDesigns - 3 months ago 18
HTML Question

JavaScript - Count how many time a button is pressed(function)

I'm trying to count how many times a button is pressed, however I dont think this is right, because the count button keeps incrementing even if the 'Saying Hello' button isn't clicked

Any thoughts?

<!DOCTYPE html>

<html>
<head>
<title>JSExample</title>
</head>

<body>

<script type="text/javascript">
function hello() {
alert("Hello there!");
}

var countClicks = 0;

function upCount() {

if(document.getElementById('hello').onclick = "hello()") {
countClicks++;
alert(countClicks);
return true;
} else {
return false;
}

}

</script>

<p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p>

<p><input type="button" name="click" value="Counting" id="click" onclick="upCount();"/></p>

</body>

</html>

Answer

Y, i don't exactly understand your problem. Right now on click 'Saying hello' you are calling a function 'hello()' which only pops up an alert with 'Hello there'. On clicking 'Counting' button, you are checking a very strange condition that i don't exactly understand and then increment the value. So, if you want to count how many times 'say hello' was clicked, and then present it with 'Counting' button, use this code.

<!DOCTYPE html>

<html>
    <head>
        <title>JSExample</title>
    </head>

    <body>

        <script type="text/javascript">
            function hello() {
               alert("Hello there!");
               countClicks++;
            }

            var countClicks = 0;

            function upCount() { 
                alert(countClicks);
            }

        </script>

        <p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p>

        <p><input type="button" name="click" value="Counting" id="click" onclick="upCount();"/></p>

    </body>

</html>

If this is not what you meant, please let me know :)