Cant sum values properly

Hello everyone!

I m having an issue summing inputs values by units of measurements.

i have two tables one for sums (grouped by unit of measurements and of first open is filled with data from database)

and form table with checkboxes

Here is fiddle: http://jsfiddle.net/vqoacdLz/12/

I want that in first table lines and quantity is calculated on checkbox check/uncheck and quantity is sum of second table inputs value by unit of measurements
but it seems i m doing something wrong :frowning:

Maybe anyone sees a fix or whats wrong?

you reset the sum to 0 in each iteration cycle.

you should rather use Array.reduce() than $().each().

if i remove sum = 0; it seems to not work at all

Will take a look at this!

This is correct. At some point you have to reset it, just not in each iteration cycle. That’s why reduce() makes so much more sense here.

so i have to make array?I do not get this a bit

If you want to use reduce(), yes. Good thing jQuery has a method for that: http://api.jquery.com/get/#get2

Summing up (input element) values from a collection (of input elements) is a standard use-case for reduce()

@Dormilich Also if i m not using $('#rtable').find('.sum_values:checked').each( how will i tell whitch checkbox is checked?

$('#rtable').find('.sum_values:checked')

Just don’t use each(), since it’s the wrong method to use.

@Dormilich I m still bad at javascript/jquery i guess this is wrong? $('#rtable').find('.sum_values:checked').reduce(function () { also console returns TypeError: $(…).find(…).reduce is not a function

Correct. The available jQuery methods can be found by looking up http://api.jquery.com/<name-of-the-method> (hint: reduce() is not a jQuery method). But I have already given you the method to link jQuery and reduce().

@Dormilich Thanks did it (whits some more help) :slight_smile:

	for(var i = 0; i < list.length; ++i) {
    if(check[i].checked){
        values.push(parseFloat(hlist[i].value));
        }else{
         values.push(parseFloat(0));
        }
    }	
    total = values.reduce(function(previousValue, currentValue, index, array){
        return previousValue + currentValue;
    });

Here’s a more structured (and readable version) using ES6 features:

var total = [...list] // list-to-array conversion
    .filter(e => e.checked) // only checked checkboxes
    .map(e => e.value) // element to value
    .map(v => parseFloat(v)) // string to number
    .reduce(((sum, val) => sum + val), 0) // numbers to sum

The same version in jQuery:

var total = $('#rtable')
    .find('.sum_values:checked')
    .get()
    .reduce(function (sum, val) {
        return sum + parseFloat(val)
    }, 0)
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.