Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple jquery sum

Tags:

jquery

math

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

`

like image 367
Danish Adeel Avatar asked Dec 21 '22 21:12

Danish Adeel


2 Answers

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/

like image 95
Alnitak Avatar answered Jan 05 '23 18:01

Alnitak


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.

like image 20
benqus Avatar answered Jan 05 '23 18:01

benqus