You are viewing limited content. For full access, please sign in.

Question

Question

How to Count Amount of Rows in a Table?

asked on September 15, 2015

We have a form that is calculating averages of scores entered in each row of a table. The table has a minimum of 2 rows, but can have upwards of 10 rows. We have the following function to calculate the scores together and get the average using a fixed number.

//Start Add row amount fields together for achievement
        $('.cf-table-block').on('blur change', '.achievementSum select', achievementsumtotal);
  
    function achievementsumtotal() {
        var s = 0;
        $('.achievementSum select').each(function () {
            s += parseNumber($(this).val());
        });
        s = s/2;
        $('.achievementSubtotal input').val((s).toFixed(2));
    }
    function parseNumber(n) {
        var f = parseFloat(n); //Convert to float number.
        return isNaN(f) ? 0 : f; //treat invalid input as 0;
    }
    //End Add row amount fields together for achievement

Our problem since the table could have more than 2 rows, how can I count the amount of rows in the table and use that to divide against to get the correct average dynamically?

1 0

Answer

APPROVED ANSWER
replied on September 15, 2015

In your function, replace

s = s/2;

with

s = s/($('.cf-table-block tr').length - 1);

I'd also suggest adding another line in the JS to run the function again when a row is deleted from the table.

1 0
replied on September 15, 2015

Alex, thank you for that! How would I add the delete check? Does the change event not catch that?

0 0
replied on September 15, 2015

I changed the code as you suggested. I think since I have multiple tables though that then numbers are not coming out correctly. I was thinking I could just add a CSS class to the table in question and then change what gave me to:

s = s/($('.achievementMeasure .cf-table-block tr').length - 1);

When I try that I start getting whole negative numbers instead of a fraction. Any ideas?

1 0
replied on September 15, 2015

Add

$(document).on('click', '.form-del-field', achievementsumtotal);

to your JS

1 0
replied on September 15, 2015

If you gave the specific table a CSS class name achievementMeasure, then use

s = s/($('.achievementMeasure tr').length - 1);
0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.