user2770982
user2770982

Reputation: 33

Can't output a simple javascript result

I am trying to list all numbers below a certain number provided in the textfield (see input) that is multiples of 3 or 5 and then add the multiples and outputting the sum (in this case changing the div#answers text to the sum.

Example: if that certain number is 10, then the multiple of 3 and 5 that is < 10, would be 3,5,6,9 and the sum of 3,5,6,9 is 23. I got all down as far as the solution goes but for the life of me can't output the answer.

<html>
    <head>
        <script>
            function myFunc() {
             var result = [];
             var sum;
             for(var i = 1; i < document.getElementById('number').value; i++) {
                if(3*i < document.getElementById('number').value) {
                  result[i] = 3*i;
             }
             if(5*i < document.getElementById('number').value) {
                result[i] = 5*i;
             }
            }
            for(i = 0; i < result.length; i++) {
               sum += result[i];
            }
           }
          document.getElementById("answers").innerHTML = sum;
    </script>
</head>
<body>
    <input type="text" id="number"  />
    <input type="button" onclick="myFunc()" value="Click for answer">
    <div id="answers"></div>
    </div>
</body>

Upvotes: 0

Views: 38

Answers (2)

Mritunjay
Mritunjay

Reputation: 25882

There were many problems in your code.

1) Assigning result out of the function. Last line.

2) You should be using result.push(3*i); not result[i]=3*i.

3) if You don't initialize variable sum it will be undefined and undefined+10=NaN

Try this

function myFunc() {
    var result = [];
    var sum=0;
    for(var i = 1; i < document.getElementById('number').value; i++) {
        if(3*i < document.getElementById('number').value) {
            result.push(3*i);
        }
        if(5*i < document.getElementById('number').value) {
            result.push(5*i);
        }
    }
    for(i = 0; i < result.length; i++) {
        sum += (result[i]);
    }
    document.getElementById("answers").innerHTML = sum;
}

Upvotes: 1

UweB
UweB

Reputation: 4110

If you tidy up the indentation in your JavaScript, you get

function myFunc() {
    var result = [];
    var sum;
    for (var i = 1; i < document.getElementById('number').value; i++) {
        if (3 * i < document.getElementById('number').value) {
            result[i] = 3 * i;
        }
        if (5 * i < document.getElementById('number').value) {
            result[i] = 5 * i;
        }
    }
    for (i = 0; i < result.length; i++) {
        sum += result[i];
    }
}
document.getElementById("answers").innerHTML = sum;

As you can see, the assignment of the sum to the result div is outside the function - this is why it won't work.

Upvotes: 2

Related Questions