- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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” −
- Related Articles
- How to trigger a button click on keyboard "enter" with JavaScript?
- JavaScript Sum function on the click of a button
- JavaScript Trigger a button on ENTER key
- Trigger a button click and generate alert on form submission in JavaScript
- How to hide a div in JavaScript on button click?
- Call the same function when clicking a Button and pressing Enter in Tkinter
- How to call a JavaScript function on click?
- How do you make a button that adds text in HTML ?
- How to click on a button with Javascript executor in Selenium with python?
- How to call a JavaScript function on a click event?
- How to add and remove names on button click with JavaScript?
- Display array items on a div element on click of button using vanilla JavaScript
- How to remove li elements on button click in JavaScript?
- Add a pressed effect on button click with CSS
- How to display JavaScript array items one at a time in reverse on button click?

Advertisements