Question comming from JavaScript beginner. I have a table created with Tabulator grid. I would like to "select" a column when one of the cells is clicked and deselect another one which was previously selected.
The code I have currently is able to select whole column when clicked but deselecting the other columns has a side effect that another column is added to the table (please run the snipplet to see). What is wrong with my code? Also is there any more elegant way to deselect the previously selected column? I am not sure if keeping the var selectedCell as a global variable is such a good idea.
var tabledata = [
{id:1, fullName:"Oli Bob", age:"12", color:"red"},
{id:2, fullName:"Mary May", age:"1", color:"blue"},
{id:3, fullName:"Christine Lobowski", age:"42", color:"green"},
];
var selectedCell = null;
var table = new Tabulator("#example-table", {
data:tabledata,
columns:[
{title:"Name", field:"fullName"},
{title:"Favourite Color", field:"color"},
],
columnDefaults:{
cellClick:function(e, cell){
if (selectedCell) {
cell.getTable().getColumns().forEach(function (column) {
column.updateDefinition( {cssClass: ""});
});
console.log(" previously selected col " + selectedCell.getColumn().getDefinition().field);
}
selectedCell = cell;
cell.getColumn().updateDefinition({cssClass: "column-selected"});
},
},
});
.column-selected {
color:red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://unpkg.com/tabulator-tables@5.5.2/dist/css/tabulator.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/tabulator-tables@5.5.2/dist/js/tabulator.min.js"></script>
</head>
<body>
<div id="example-table"></div>
</body>
</html>
I would suggest you use the cellClick
event to update the column definition based on clicked cell. Here is the example you used modified:
const tabledata = [
{ id: 1, fullName: 'Oli Bob', age: '12', color: 'red' },
{ id: 2, fullName: 'Mary May', age: '1', color: 'blue' },
{ id: 3, fullName: 'Christine Lobowski', age: '42', color: 'green' }
]
const table = new Tabulator('#example-table', {
data: tabledata,
columns: [
{ title: 'Name', field: 'fullName' },
{ title: 'Favourite Color', field: 'color' }
]
})
table.on('cellClick', (e, cell) => {
const selectedCol = cell.getColumn().getField()
table.getColumns().forEach((col) => {
col.updateDefinition({ cssClass: col.getField() === selectedCol ? 'column-selected' : '' })
})
})
.column-selected {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://unpkg.com/tabulator-tables@5.5.2/dist/css/tabulator.min.css" rel="stylesheet" />
<script src="https://unpkg.com/tabulator-tables@5.5.2/dist/js/tabulator.min.js"></script>
</head>
<body>
<div id="example-table"></div>
</body>
</html>