I would like to save column names to database and ask user to select the columns which need to save, is there any way to add checkbox for every header to save it?
I don't want to select any row.. I just need column names.
One way would be to inject the checkbox directly into title of the column definition. You can then assign an onclick
event to the checkbox to execute the action you need. In your case, saving column names to database. Or you can get all checked boxes first and perform an action based on that. Here is an example that shows both:
const data = [
{ id: 1, name: 'Billy Bob', age: '12', gender: 'male', height: 1, col: 'red', dob: '', cheese: 1 },
{ id: 2, name: 'Mary May', age: '1', gender: 'female', height: 2, col: 'blue', dob: '14/05/1982', cheese: true },
{ id: 10, name: 'Margret Marmajuke', age: '16', gender: 'female', height: 5, col: 'yellow', dob: '31/01/1999' }
]
const headerCheckbox = (value) =>
`<input type="checkbox" value="${value}" onclick="event.stopPropagation();boxClick(this)">`
const table = new Tabulator('#table', {
data: data,
columns: [
{ title: headerCheckbox("name") + ' Name', field: 'name' },
{ title: headerCheckbox("age") + ' Age', field: 'age' },
{ title: headerCheckbox("gender") + ' Gender', field: 'gender' },
{ title: headerCheckbox("height") + ' Height', field: 'height' },
{ title: headerCheckbox("color") + ' Color', field: 'col' }
]
})
// Individual checkbox actions
function boxClick(checkbox) {
const action = checkbox.checked
? `Save column '${checkbox.value}' to database`
: `Remove column '${checkbox.value}' from database`
console.clear()
console.log(action)
}
// Get all checked boxes first, then perform an action
document.getElementById('saveColumns').addEventListener('click', (e) => {
const checkboxes = document.querySelectorAll('.tabulator-headers input')
const colsToSave = [...checkboxes].filter((checkbox) => checkbox.checked).map((box) => box.value)
console.clear()
console.log('Columns to save: ', colsToSave)
})
<link href="https://unpkg.com/tabulator-tables@5.5.2/dist/css/tabulator.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@5.5.2/dist/js/tabulator.min.js"></script>
<div id="table"></div>
<p>
<button id="saveColumns">Save columns</button>