We can use jQuery to increment the value of a variable on a user click very easily by using the jQuery click() method.

var i = 0;
$("#div1").click(function(){
  i++; //Same as i = i + 1
});

Let’s see a couple of examples of this.


In this first example, we will simply have a variable in the background that we will increment whenever a user clicks a button. Here is the HTML setup.

In our JavaScript and jQuery code, we will simply have a global variable called value1. Each time someone clicks the button, we will increment our variable by 1.

Here is the code:

var value1 = 0;
$("#button1").click(function(){
  value1++;
});

If you are using WordPress, don’t forget to change the $ to jQuery as below:

var value1 = 0;
jQuery("#button1").click(function(){
  value1++;
});

In this next example, we will have a value in our HTML and show how to inclement that for the user to see.

Using jQuery to Increment an HTML Value on a User Click

This example will be the same as the previous one, but instead of having a global variable that we increment, we will increment a value in our HTML div.

Here is our HTML code:

0
Increment above value by 1

In our JavaScript code, the additional steps we need to take are to get the value in our div, increment its value, and then update the div with the new value.

To do this we just need to make use of the jQuery text() method to get the value from our div, and to also update that value for the user to see.

Here is the JavaScript and jQuery code:

$("#click-me").click(function(){
  //Get the value in our div and convert to a number, which starts at 0
  var userText = Number($("#value1").text());
  
  //Increment the value by 1
  userText++;
  
  //Update the div for the user to see
  $('#value1').text(userText);
});

The final code and output for this example of using jQuery to increment an HTML value on a user click is below:

Code Output:

0
Increment above value by 1

Full Code:

0
Increment above value by 1

Hopefully this article has been useful to help you understand how to use jQuery to increment a value on click.

Categorized in:

jQuery,

Last Update: March 12, 2024