how to get total value using sum().js?

how to get total value using sum().js?

naksuriyanaksuriya Posts: 3Questions: 1Answers: 0
edited November 2015 in Free community support

My html is like this

<table id='example'>
  <tr>
   <th>id</th>
   <th>price</th>
 </tr>

  <tr>
   <td>1</td>
   <td><input type='text' value='1'  class='test'></td>
 </tr>

  <tr>
   <td>1</td>
   <td><input type='text' value='2' class='test'></td>
 </tr>

</table>
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
    return this.flatten().reduce( function ( a, b ) {
        if ( typeof a === 'string' ) {
            a = a.replace(/[^\d.-]/g, '') * 1;
        }
        if ( typeof b === 'string' ) {
            b = b.replace(/[^\d.-]/g, '') * 1;
        }

        return a + b;
    }, 0 );
} );

Answers

  • naksuriyanaksuriya Posts: 3Questions: 1Answers: 0

    var table = $('#example').DataTable(); var sum = table.column(4).data().sum(); alert(sum);
  • jLinuxjLinux Posts: 981Questions: 73Answers: 75

    Was the last post your resolution?

    You didnt give any detail on what you need.. youre just like "heres code.. fix it"

  • naksuriyanaksuriya Posts: 3Questions: 1Answers: 0
    edited November 2015

    Sorry for that sir. This is my code. my problem is how to get that class "test" in my api colums?

     
    var table = $('#my_table').DataTable( {
                "bProcessing": true,
                 "sAjaxSource": base_url + "core/test",
                "footerCallback": function (row, data, start, end, display) {
                var api = this.api(),
                    data;
    
    
                
               total = api
                        .columns(2 ,  {
                            page: 'current'
                        })
                        .data()
                        .sum();
    
                    
     
    
                // UPDATE FOOTER //
                $(api.column(2).footer()).html( total_number );
    
               
    
            },
    
    
  • allanallan Posts: 63,356Questions: 1Answers: 10,444 Site admin

    The DataTables API isn't going to help a huge amount here (specifically the sum() method) since the data is in the input elements rather than in the data objects for each row - it could be done, but its probably as easy to use a simple for loop.

    First get all of the input elements:

    var inputs = $( 'input.test', api.rows().nodes() );
    

    Then do a for (or $.each) loop over the inputs and sum up their values.

    Allan

This discussion has been closed.