Peluco
Peluco

Reputation: 75

How do I input numbers in Javascript?

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>

Upvotes: 2

Views: 910

Answers (3)

jkyadav
jkyadav

Reputation: 1282

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.

Upvotes: 0

Peluco
Peluco

Reputation: 75

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>

Upvotes: 0

blex
blex

Reputation: 25648

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

Upvotes: 3

Related Questions