Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create an increment of 10 value once you click a button in JavaScript?
To create a button that increments a value by 10 each time it's clicked, you can use JavaScript's click() event listener along with parseInt() to handle numeric operations.
Basic Approach
The core concept involves storing a counter variable, adding 10 to it on each button click, and updating the display element with the new value.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Increment by 10</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<div id="add">10</div>
<div id="sequenceValue">0</div>
<button id="addSequenceOf10">Add 10 Each Time</button>
<script>
let addValue = 0;
$("#addSequenceOf10").click(function() {
const actualValue = parseInt($("#add").html());
addValue = addValue + actualValue;
$("#sequenceValue").html(addValue);
});
</script>
</body>
</html>
Pure JavaScript Version
Here's the same functionality using vanilla JavaScript without jQuery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Increment by 10</title>
</head>
<body>
<div id="add">10</div>
<div id="sequenceValue">0</div>
<button id="addSequenceOf10">Add 10 Each Time</button>
<script>
let addValue = 0;
document.getElementById("addSequenceOf10").addEventListener("click", function() {
const actualValue = parseInt(document.getElementById("add").innerHTML);
addValue += actualValue;
document.getElementById("sequenceValue").innerHTML = addValue;
});
</script>
</body>
</html>
How It Works
The script follows these steps:
-
Initialize: Set
addValueto 0 as the starting counter - Event Listener: Attach a click event to the button
-
Parse Value: Use
parseInt()to convert the HTML content to a number - Increment: Add 10 to the current counter value
- Update Display: Show the new total in the display element
Expected Output
First click: 10 Second click: 20 Third click: 30 Fourth click: 40 ... and so on
Key Points
-
parseInt()ensures proper numeric addition instead of string concatenation - The counter variable persists between clicks, maintaining the running total
- The increment value (10) is stored in a separate div for easy modification
- Both jQuery and vanilla JavaScript approaches achieve the same result
Conclusion
This pattern demonstrates basic DOM manipulation and event handling in JavaScript. Each button click successfully increments the displayed value by 10, creating a running total that updates dynamically.
Advertisements
