简体   繁体   中英

How To Load Two Sourced Data into DataTables on Button Click event

Can you please take a look at This Demo and let me know how I can declare and intial an DataTable and then load sourced data into the table on demand (by clicking on buttons) What I need to do is to Clear or Truncate the Table <td>s before adding/Loading new data

 var dataSet1 = [ [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ], [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ], [ "Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000" ], [ "Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060" ], [ "Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700" ] ]; var dataSet2 = [ [ "Dai Rios", "Personnel Lead", "Edinburgh", "2290", "2012/09/26", "$217,500" ], [ "Jenette Caldwell", "Development Lead", "New York", "1937", "2011/09/03", "$345,000" ], [ "Yuri Berry", "Chief Marketing Officer (CMO)", "New York", "6154", "2009/06/25", "$675,000" ], [ "Caesar Vance", "Pre-Sales Support", "New York", "8330", "2011/12/12", "$106,450" ], [ "Doris Wilder", "Sales Assistant", "Sidney", "3023", "2010/09/20", "$85,600" ], [ "Angelica Ramos", "Chief Executive Officer (CEO)", "London", "5797", "2009/10/09", "$1,200,000" ], [ "Gavin Joyce", "Developer", "Edinburgh", "8822", "2010/12/22", "$92,575" ] ]; var tbl = $('#example').DataTable(); $("#load1").on("click", function(){ }); $("#load2").on("click", function(){ }); 
 @import 'https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css'; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script> <button id="load1" class="btn btn-default" type="submit">Load Dataset 1</button> <button id="load2" class="btn btn-default" type="submit">Load Dataset 2</button> <table id="example" class="display" width="100%"> <thead> <tr> <th>Name</th> <th>Office</th> <th>Subscriber</th> <th>Share</th> <th>Subscriber Date</th> <th>Balance</th> </tr> </thead> </table> 

Basically you need to clear the table then add the new rows before drawing the table again:

$("#load1").on("click", function(){
    tbl.clear().rows.add(dataSet1).draw();

});

$("#load2").on("click", function(){
    tbl.clear().rows.add(dataSet2).draw();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM