2

I'm doing a HTML web that accept numbers separated by "," and then get the sum of all. I have tried this code, but don't work.

<!DOCTYPE html>
<html>
<body>

<p>Input the numbers you want separated by ","</p>
<input id="num"></input>
<button onclick="sumAll1()">click!</button>

<p id="total"></p>

<script>
function sumAll1(){
document.getElementById("total").innerHTML = sumAll(document.getElementById("num").innerHTML.value);

}
function sumAll() {

    var i, sum = 0;
    for(i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
} 

</script>

</body>
</html>
1
  • <input id="num"></input> should be <input type="text" id="num"/> Commented Jul 15, 2015 at 18:41

3 Answers 3

3

function sumAll1(){
  var sum = document.getElementById("num").value.split(',').reduce(add, 0);
  document.getElementById("total").innerHTML = sum;
}

function add(a, b) {
    return +a + +b;
}
<p>Input the numbers you want separated by ","</p>
<input type="text" id="num"/>
<button onclick="sumAll1()">click!</button>

<p id="total"></p>

split(',') will create an array of Strings that contain your numbers.

Then, using reduce, the add() function is applied to them.

In add(), I used the unary operator + to convert the Strings to Numbers (e.g: +"1" becomes 1).

Sign up to request clarification or add additional context in comments.

2 Comments

Additionnal note on this perfectly fine answer: depending on what [the reader] is trying to achieve, parseFloat or parseInt functions could also replace the unary operators.
@JeffNoel Totally true, I just used the unary operator to avoid cluttering the code. And thanks
0

Now I do this:

<!DOCTYPE html>
<html>
<body>

<p>Input the numbers you want separated by ","</p>
<input type="text" id="num"/>
<button onclick="sumAll()">click!</button>

<p id="total"></p>

<script>

function sumAll(){
var i,suma=0;
var array = document.getElementById("num").value.split(',');
for(i = 0; i < array.length; i++) {
        suma += parseInt(array[i]);
    }
document.getElementById("total").innerHTML = suma;
}
</script>

</body>
</html>

Comments

0

Change you javascript code as below.

<script>
function sumAll1(){
document.getElementById("total").innerHTML = sumAll(document.getElementById("num").innerHTML.value);

}
function sumAll(arguments) {
    var values=arguments.split(',');
    var i, sum = 0;
    for(i = 0; i < values.length; i++) {
        sum += values[i];
    }
    return sum;
} 

</script>

Try this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.