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
Selected Reading
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.
Example
The code for this will be −
JavaScript Code −
function myFunc() {
var num = document.getElementById('digits').value;
var tot = 0;
num.split('').forEach( function (x) {
tot = tot + parseInt(x,10);
});
document.getElementById('output').innerHTML = tot;
}
HTML Code −
<input id="digits" /> <button onClick="myFunc()">Submit</button> <div id="output"></div>
Output
And the output will be &miuns;

After clicking “Submit” −

Advertisements
