4

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..
}
Daniel Hunter
  • 2,546
  • 6
  • 28
  • 34

2 Answers2

9

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);
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Wow, that's pretty much exactly what I posted. – nrabinowitz Mar 09 '12 at 01:21
  • Thanks jfriend00. The function form works. can you help me understand ,10 || 0? What is this doing? – Daniel Hunter Mar 09 '12 at 01:28
  • 1
    @DanielHunter - See these questions: http://stackoverflow.com/questions/9380039/default-parseint-radix-to-10 and http://stackoverflow.com/questions/850341/workarounds-for-javascript-parseint-octal-bug – Jared Farrish Mar 09 '12 at 01:30
  • 1
    @DanielHunter - the `parseInt() || 0` is adding to `total` either the result of `parseInt()` or, if that's not a truthy value (like if the field is blank or doesn't contain a number), then it's adding 0. It's just a shortcut for testing the result of `parseInt()` with `if (!isNaN(x))` that saves a lot of lines of code because you don't need the if statement. The `10` is the radix argument to `parseInt()` and should almost always be used because without it, `parseInt()` can guess the radix based on the content. – jfriend00 Mar 09 '12 at 01:37
4

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);
});
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165