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..
}
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);
}
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With