JavaScript increment counter number on button click | Example code

The purist way to do this would be to add event handlers to the button, to increment a counter number in JavaScript.

JavaScript increment a counter examples

HTML examples code with ‘Plain‘ JavaScript:-

1. Increment number variable value

Create a JavaScript variable and increment that variable when press a button (without submit the form).

Counterexample: how to increment a JavaScript variable based on a web page button press event.

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript">
        var counter = 0;
        function increment(){
            counter++;
            console.log(counter);
        }
    </script>

</head>
<body>
  <input type="button" onClick="increment()" value="Increment"/>
</body>
</html>

Output:

JavaScript increment counter number on button click

2. Increment element value

Let’s make a counter variable that increases the value when you click a button. We are using two elements in HTML.

First text and second id button, on clicking a button text input will increase current value by one.

<!DOCTYPE html>
<html>
<body>
    <form>
     <input type="text" id="number" value="0"/>
     <input type="button" onclick="incrementValue()" value="Increase" />
 </form>

 <script>
    function incrementValue()
    {
        var value = parseInt(document.getElementById('number').value, 10);
        value = isNaN(value) ? 0 : value;
        value++;
        document.getElementById('number').value = value;
    }
</script>

</body>
</html>

Output:

Increment HTML element value JavaScript

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.