hannahB
hannahB

Reputation: 11

How do I make a button display the number of times it's been clicked in javascript?

I am creating a button where the status bar needs to be updated after each button click to display “You have generated numbers x times” where x is the number of times the button has been clicked since the page has been loaded. I

Here is my entire code so far (I'm making a random number generator):

<!DOCTYPE html>
<html>
<body>
    <font face="Times New Roman" style="color:MediumOrchid">
        <h1 align="left"> Play At Your Own Risk! </h1>
    </font>
    <button onclick="randomNum ()"> Please click the button to roll the dice </button>
    <p id="demo"> </p>


    <script>
    function randomNum ()
    {
        var listOfNumbers=[];
        var stringOutput="";
        for (i=0;i<5;i++) {
            listOfNumbers.push(Math.floor(Math.random()*59)+1);
            stringOutput += listOfNumbers[i] + "";
        }
        document.getElementById("demo").innerHTML = stringOutput;
    }
    </script>
</body>
</html>

Upvotes: 1

Views: 1915

Answers (3)

Ray Joe
Ray Joe

Reputation: 202

Is this what you're asking for?

HTML code:

<button id="btn">click</button>
<p id="num"></p>

JavaScript code:

var btn = document.getElementById('btn'); //Grabs the button's ID
btn.addEventListener("click", points, false); //Adds an event listener to the button
var counts = 0; // counting starts with 0

function points(num) { // where the magic happens
    counts++; // 0 gets increased by one every time the user clicks
    num = document.getElementById('num');
    num.innerHTML = counts; // displays the numbers
}

DEMO

Upvotes: 0

Andy
Andy

Reputation: 63569

You don't need jQuery for this:

HTML

<button id="button">Clicked 0 times</button>

JS

var count = 0;
var button = document.getElementById('button');

button.onclick = updateStatus;

function updateStatus() {
    button.textContent = 'Clicked ' + ++count + ' times';
}

DEMO

Upvotes: 1

AlwaysNull
AlwaysNull

Reputation: 348

You can create a global variable to store the number of clicks. In the event handler for the button display the current clicks and increment that. JQuery is your friend :)

Upvotes: 2

Related Questions