简体   繁体   中英

Adding extra column to datatables

I need to add columns (header) to a datatable. In the example I have filter on period, if I choose period from January 2016 until May 2016 then I need to add column <th> like this

Buyer|January 2016 | February 2016 | April 2016 | May 2016 | 

But when I pick period from January 2016 until June 2016

Buyer|January 2016 | February 2016 | April 2016 | May 2016 | June 2016

Any idea??? I'm using DataTables.

You can use a similar function like this drawDataTable, wrap the months in an array, clear the header row, and finally add the headers.

 (function() { var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var sel1 = document.querySelector('#sel1'); var sel2 = document.querySelector('#sel2'); var year = 2016; var table = document.querySelector('table'); function fillMonths(month, select) { var element = document.createElement('option'); element.textContent = month; select.appendChild(element); } months.forEach(function(month) { fillMonths(month, sel1); }); months.forEach(function(month) { fillMonths(month, sel2); }); function drawDataTable(selected) { var rest = months.slice(months.indexOf(selected[0]), months.indexOf(selected[1]) + 1); var nodes = table.rows[0]; while (nodes.children.length > 1) { var cell = nodes.children[1]; nodes.removeChild(cell); } rest.forEach(function(month) { var header = document.createElement('th'); header.textContent = month + ' ' + year; table.rows[0].appendChild(header); }); } var monthSelected = ['January', 'January']; drawDataTable(monthSelected); sel1.addEventListener('change', function(event) { monthSelected[0] = event.target.value; drawDataTable(monthSelected); }); sel2.addEventListener('change', function(event) { monthSelected[1] = event.target.value; drawDataTable(monthSelected); }); })(); 
 body { font-family: "Open Sans", sans-serif; } table { border-collapse: collapse; } th { border: 2px solid black; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Made with Thimble</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Choose date</h1> Month <select id="sel1"></select> to <select id="sel2"></select> <table> <tr> <th>Buyer</th> </tr> </table> <script src="script.js"></script> </body> </html> 

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