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
Enter a number and write a function that adds the digits together on button click in JavaScript
We are required to write a JavaScript program that provides users an input to fill in a number.
And upon filling when the user clicks the button, we should display the sum of all the digits of the number.
HTML Structure
First, let's create the HTML elements needed for our application:
<input id="digits" type="number" placeholder="Enter a number" /> <button onClick="myFunc()">Submit</button> <div id="output"></div>
JavaScript Implementation
Here's the JavaScript function that calculates the sum of digits:
function myFunc() {
var num = document.getElementById('digits').value;
var tot = 0;
// Convert to string and split into individual digits
num.split('').forEach(function(x) {
tot = tot + parseInt(x, 10);
});
document.getElementById('output').innerHTML = "Sum of digits: " + tot;
}
Complete Working Example
Here's the complete HTML page with the digit sum calculator:
<!DOCTYPE html>
<html>
<head>
<title>Digit Sum Calculator</title>
</head>
<body>
<h3>Enter a number to calculate sum of its digits</h3>
<input id="digits" type="number" placeholder="Enter a number" />
<button onClick="myFunc()">Submit</button>
<div id="output"></div>
<script>
function myFunc() {
var num = document.getElementById('digits').value;
var tot = 0;
if (num === '') {
document.getElementById('output').innerHTML = "Please enter a number";
return;
}
// Convert to string and split into individual digits
num.split('').forEach(function(x) {
if (!isNaN(x) && x !== '') {
tot = tot + parseInt(x, 10);
}
});
document.getElementById('output').innerHTML = "Sum of digits: " + tot;
}
</script>
</body>
</html>
How It Works
The function works by following these steps:
- Get the input value from the text field using
getElementById - Initialize a total variable to store the sum
- Split the number string into individual characters using
split('') - Loop through each digit using
forEach - Convert each digit to an integer using
parseIntand add to total - Display the result in the output div
Example Usage
If you enter the number 1234, the function will:
- Split it into ['1', '2', '3', '4']
- Calculate: 1 + 2 + 3 + 4 = 10
- Display: "Sum of digits: 10"
Enhanced Version with Input Validation
function myFunc() {
var num = document.getElementById('digits').value;
var tot = 0;
// Input validation
if (num === '' || isNaN(num)) {
document.getElementById('output').innerHTML = "Please enter a valid number";
return;
}
// Handle negative numbers by taking absolute value
num = Math.abs(num).toString();
num.split('').forEach(function(x) {
tot += parseInt(x, 10);
});
document.getElementById('output').innerHTML = "Sum of digits: " + tot;
}
Conclusion
This digit sum calculator demonstrates DOM manipulation and string processing in JavaScript. The function splits a number into individual digits and calculates their sum, providing immediate feedback to users through button interaction.
