Danish Adeel
Danish Adeel

Reputation: 730

Simple jquery sum

I have unknown number of input fields, having class "add" I just wants to sum these with jquery, dont know where I am wrong.

<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">
<input name="add" class="add" type="text">

<input type="button" value="" onClick="add()" />

`

function add(){
        val = 0;
        $(".add").each(function() {      
            str = (parseInt(this.value))
            sum=str+str
        });
        alert (sum)
    }

`

Upvotes: 4

Views: 52415

Answers (3)

mark.monteiro
mark.monteiro

Reputation: 2931

If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce() method. You will need to convert your JQuery object into an array first:

function add() {
     return $('.add').toArray().reduce(function(sum,element) {
         return sum + Number(element.value);
     }, 0);
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Upvotes: 0

benqus
benqus

Reputation: 1139

function add(){
    var sum = 0;
    $(".add").each(function() {
        var val = parseInt($(this).val(), 10)
        sum += (!isNaN(val) ? val : 0);
    });
    alert(sum);
}

Edit: Sharp eyes, got the parenthesis... =) And the space.

Upvotes: 4

Alnitak
Alnitak

Reputation: 339786

You're never actually adding stuff into sum:

function add() {
    var sum = 0;
    $(".add").each(function() {   
        sum += +this.value;
    });
    return sum; // an add function shouldn't really "alert"
}

If the intention is to only support whole numbers, use parseInt(this.value, 10) [note the radix parameter] instead of +this.value:

function add() {
    var sum = 0;
    $(".add").each(function() { 
        var str = this.value.trim();  // .trim() may need a shim
        if (str) {   // don't send blank values to `parseInt`
            sum += parseInt(str, 10);
        }
    });
    return sum;
}

See http://jsfiddle.net/alnitak/eHsJP/

Upvotes: 7

Related Questions