Learning
Learning

Reputation: 127

Get Table column average from ajax response

Hi I have this code which returns a filtered table (with hidden headers of customer|comments|rating)

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "w31.php",
        data: {
            value: '8'
        },
        success: function(response) {
            $('.tbl').append(response);
        }
    });
});

The response code is actually

<table>
    <tr>
        <td valign='top'>David</td>
        <td valign='top'>A bit dry</td>
        <td valign='top'>3</td>
    </tr>
    <tr>
        <td valign='top'>Susan</td>
        <td valign='top'>I liked it</td>
        <td valign='top'>4</td>
    </tr>
    <tr>
        <td valign='top'>Richard</td>
        <td valign='top'>Had better</td>
        <td valign='top'>2</td>
     </tr>
</table>

What I want to do is get an average of the rating column. Is this possible?

Upvotes: 1

Views: 155

Answers (1)

4b0
4b0

Reputation: 22323

On success, after binding your table you can calculate the average rating.

var sum = 0, row = $('.tbl tr');

row.each(function() {
  sum += parseFloat($(this).children('td').eq(2).text());
});

row.each(function() {
  var tds = $(this).children('td'), 
    value = parseFloat(tds.eq(2).text());
  console.log((value/sum).toFixed(3)); // do whatever you want this value.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tbl">
  <tr>
    <td valign='top'>David</td>
    <td valign='top'>A bit dry</td>
    <td valign='top'>3</td>
  </tr>
  <tr>
    <td valign='top'>Susan</td>
    <td valign='top'>I liked it</td>
    <td valign='top'>4</td>
  </tr>
  <tr>
    <td valign='top'>Richard</td>
    <td valign='top'>Had better</td>
    <td valign='top'>2</td>
  </tr>
</table>

Upvotes: 1

Related Questions