Cant sum values properly

jquery

#1

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?


#2

you reset the sum to 0 in each iteration cycle.

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


#3

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

Will take a look at this!


#4

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.


#5

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


#6

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()


#7

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


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

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


#9

@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


#10

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().


#11

@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;
    });

#12

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)