我想将列名保存到数据库并要求用户选择需要保存的列,有没有办法为每个标题添加复选框来保存它?
我不想选择任何行..我只需要列名。
一种方法是将复选框直接插入到列定义的标题中。然后,您可以将
onclick
事件分配给复选框以执行您需要的操作。在您的情况下,将列名保存到数据库中。或者,您可以先获取所有复选框,然后根据该复选框执行操作。这是一个显示两者的示例:
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/[email protected]/dist/css/tabulator.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"></script>
<div id="table"></div>
<p>
<button id="saveColumns">Save columns</button>