Week 4: Lesson5 vid: Sum Integers Example

take numbers

by Lucille Kenney

HTML

<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>

CSS

body {
    font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.428571429;
    color: #333;
}
.button {
    border: 1px solid #888888;
    color: #ffffff;
    font-family: Arial;
    font-size: 15px;
    font-weight: bold;
    font-style: normal;
    height: 20px;
    width: 82px;
    line-height: 20px;
    padding: .5em;
    text-align: center;
    background-color: #614C26;
}
.button:hover {
    border: 2px solid #000;
}
label {
    display: inline-block;
}

JavaScript

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;
}