Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum values of a javascript array?

Tags:

arrays

jquery

sum

I have looked at a lot of different varriations of this question but i cant seem to find one that is particular to what i am doing.

I have input fields that are dynamicaly created by a php/mysql query. the values are numbers and they share a common class

<?php
   foreach ($garment_sizes as $key =>$value){echo '<input type="number" class="size_select" name="'.$value.'" onchange="qty_update()"/><label class="size_label">'. strtoupper($value).'</label>';
   }
?>

Resulting HTML:

<input type="number" class="size_select" name="s" onchange="qty_update()"/>
<label class="size_label">S</label>
<input type="number" class="size_select" name="m" onchange="qty_update()"/>
<label class="size_label">M</label> <!-- etc -->

I want to create a function to sum all the fields with this class "size_select"

function qty_update(){
    var values = $('.size_select').serializeArray();
    //having trouble writing the loop here to sum the array..
}
like image 927
Daniel Hunter Avatar asked Dec 12 '22 04:12

Daniel Hunter


2 Answers

To sum all fields that match a particular selector, you can do this:

var total = 0;
$('.size_select').each(function() {
    total += parseInt($(this).val(), 10) || 0;
});

// the variable total holds the sum here

In function form:

function sumSizes() {
    var total = 0;
    $('.size_select').each(function() {
        total += parseInt($(this).val(), 10) || 0;
    });
    return(total);
}
like image 140
jfriend00 Avatar answered Dec 25 '22 11:12

jfriend00


Here's one quick approach. Note that, if you're using jQuery, you should generally use jQuery to assign event handlers, as it's more flexible than doing so directly in the HTML markup:

$('input.size_select').change(function() {
    var sum = 0;
    $('input.size_select').each(function() {
         sum += parseInt($(this).val()) || 0
    });
    console.log(sum);
});
like image 20
nrabinowitz Avatar answered Dec 25 '22 12:12

nrabinowitz