Skip to content

JavaScript increment counter number on button click | Example code

  • by

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 pressing a button (without submitting the form).

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

<!DOCTYPE html>

    <script type="text/javascript">
        var counter = 0;
        function increment(){

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


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>
     <input type="text" id="number" value="0"/>
     <input type="button" onclick="incrementValue()" value="Increase" />

    function incrementValue()
        var value = parseInt(document.getElementById('number').value, 10);
        value = isNaN(value) ? 0 : value;
        document.getElementById('number').value = value;



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

Your email address will not be published. Required fields are marked *