Javascript array sum values?

I have looked at many different variations of this question, but I cannot find what is especially important for what I am doing.

I have input fields that are dynamically created using php / mysql query. values ​​are numbers and they have 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>'; } ?> 

HTML Result:

 <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 fields with this class "size_select"

 function qty_update(){ var values = $('.size_select').serializeArray(); //having trouble writing the loop here to sum the array.. } 
+4
source share
2 answers

To summarize all fields matching 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); } 
+9
source

Here is one quick approach. Note: if you use jQuery, you should usually use jQuery to assign event handlers, as it is more flexible than directly using HTML markup:

 $('input.size_select').change(function() { var sum = 0; $('input.size_select').each(function() { sum += parseInt($(this).val()) || 0 }); console.log(sum); }); 
+4
source

Source: https://habr.com/ru/post/1400495/


All Articles