Суммирование скрытого столбца в DataTables после фильтрации

public void saveUrl(final String filename, final String urlString)
        throws MalformedURLException, IOException {
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
        in = new BufferedInputStream(new URL(urlString).openStream());
        fout = new FileOutputStream(filename);

        final byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1) {
            fout.write(data, 0, count);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
}

Вам нужно будет обрабатывать исключения, возможно, внешние для этого метода.

0
задан user999684 17 January 2019 в 02:06
поделиться

1 ответ

Собрал быстрый и грязный пример, чтобы начать. По сути, таблица с функцией 'draw' сработает при поиске или фильтровании события. Оттуда вы перебираете все видимые отфильтрованные строки, используя это: { filter : 'applied'}

Запустите этот фрагмент и найдите «Нью-Йорк». Затем проверьте консоль, чтобы увидеть, как ведут себя данные и числа.

Или эту скрипку, если вы предпочитаете ...

var mytable = new Object();

var tableData = [
    {name: 'Clark Kent', city: 'Metropolis', numCol: '10', numCol2: '6'},
    {name: 'Bruce Wayne', city: 'New York', numCol: '', numCol2: '12'},
    {name: 'Steve Rogers', city: 'New York', numCol: '30', numCol2: '10'},
    {name: 'Peter Parker', city: 'New York', numCol: '44', numCol2: ''},
    {name: 'Thor Odinson', city: 'Asgard', numCol: '55', numCol2: '15'}
	];

mytable = $('#mytable').DataTable({
    "search": {
        "regex": true
    },
	  sDom: 'lrftip',
    data: tableData,
    columns: [
    	{data: 'name', title: 'Name'},
    	{data: 'city', title: 'City'},
      {data: 'numCol', title: 'Number'},
      {data: 'numCol2', title: 'Hidden Num', visible: false}
    ], 
    columnDefs: [
        { className: "sum", "targets": [2] },
    ]
	});
  
   
mytable.on( 'draw', function () {
    console.log( 'Redraw occurred at: '+new Date().getTime() );
    var myCount = 0;
    var totalSum = 0;
    mytable.rows( { filter : 'applied'} ).every(function (rowIdx, tableLoop, rowLoop) {
            var data = this.data();
            
            console.log('num1: ' + data.numCol + ' num2: ' + data.numCol2);
            
            if (data.numCol !== '') {
            		//Add to counter                
                myCount += 1;
            }
            
            if (data.numCol2 !== '') {
            	//Sum it up	
              totalSum += parseInt(data.numCol2); 
            }
            
        });
        console.log('myCount: ' + myCount + ' totalSum: ' + totalSum);
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

<div class="table-responsive">

<table id="mytable" class="table nowrap table-hover table-striped dataTable">
    <thead>
      <tr>
        <th>Name</th>
        <th>City</th>
        <th>Number1</th>
        <th>Number2</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
    <tfoot id="mytableFoot">
      <tr>
        <th>Name</th>
        <th>City</th>
        <th>Number1</th>
        <th>Number2</th>
      </tr>
    </tfoot>
  </table>
</div>

Надеюсь, это поможет.

0
ответ дан Scott 17 January 2019 в 02:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: