Danish Adeel Danish Adeel - 6 months ago 35
jQuery Question

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


`

Answer

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/