<h3>Example for video 4.5</h3>
<p>Allow the user to enter a series of numbers separated by spaces. When the user clicks a button, calculate the sum of the numbers entered. Ignore non-numeric input.</p>
<label for="nums">Enter a set of integers separated by spaces</label>
<input type="text" size="30" id="nums">
<div id="doit" class="button">Do it!</div>
<div>The sum is <span id="sum"></span>
</div>
var button = document.getElementById("doit");
button.onclick = function () {
// get the value from the input field (a string)
var numbers = document.getElementById("nums").value;
// turn the string into an array, dividing at spaces
var numArray = numbers.split(" ");
var sum = 0;
// for each item in the array
for (var i = 0; i < numArray.length; i++) {
// turn it into a number
var n = parseInt(numArray[i]);
// if we got a valid result from parseInt()
if (n) {
// add the number to our sum
sum += n;
}
}
console.log("sum is " + sum);
document.getElementById("sum").innerHTML = sum;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.