UNPKG

simple-datatables

Version:

A lightweight, dependency-free JavaScript HTML table plugin.

103 lines (99 loc) 4.61 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/svg+xml" href="../../favicon.svg"> <title>Column manipulation - simple-datatables</title> <!-- DataTable Styles --> <link rel="stylesheet" href="../dist/css/style.css"> <!-- Demo Styles --> <link rel="stylesheet" href="../demo.css"> </head> <body> <header> <h1> <a href="../../">simple-datatables</a> </h1> <a href="../../documentation">Documentation</a> <a href="../">Demos</a> </header> <h2>Column manipulation</h2> <table id="demo-table"></table> <script type="module"> import { DataTable } from "../dist/module.js" const columnData = [ { // Select the first column ... select: 0, // ...add a random number (age) to the cells render: data => `${data} (${(Math.floor(Math.random() * (70-18))+18)})` }, { // select the fourth column ... select: 3, // ... let the instance know we have datetimes in it ... type: "date", // ... pass the correct datetime format ... format: "YYYY/DD/MM", // ... sort it ... sort: "desc" } ] // Customise our labels const labelData = { placeholder: "Search students...", searchTitle: "Search within students", perPage: "students per page", noRows: "No students to display", info: "Showing {start} to {end} of {rows} students (Page {page} of {pages} pages)" } // Instantiate fetch("datatable.json").then( response => response.json() ).then( data => { const datatable = new DataTable("#demo-table", { data: { headings: Object.keys(data[0]), data: data.map(item => Object.values(item)) }, columns: columnData, labels: labelData, type: "string" }) // Wait for the instance to finish rendering // and add a new column datatable.on("datatable.init", () => { fetch("datatable.column.json").then(response => response.json()) .then(column => { // Render a button column.render = (value, _td, rowIndex, _cellIndex) => `${value}%<button type='button' data-id='${rowIndex}' class='btn btn-sm btn-primary pull-right notify'>Click Me</button>` // the dataIndex property is the correct index of the row in the data array, not the rowIndex // which will be -1 if not rendered or wrong if the we're not on page 1 datatable.columns.add(column) }) }) datatable.dom.addEventListener("click", e => { if (e.target.nodeName === "BUTTON" && e.target.hasAttribute("data-id")) { const index = parseInt(e.target.getAttribute("data-id"), 10) const row = datatable.data.data[index].cells let message = [ "This is row ", (e.target.closest("tr").rowIndex + 1), " of ", datatable.options.perPage, " rendered rows and row ", (index + 1), " of ", datatable.data.length, " total rows." ] const data = [].slice.call(row).map(cell => cell.data) message = message.join("") message = `${message}\n\nThe row data is:\n${JSON.stringify(data)}` alert(message) } }) } ) </script> </body> </html>