I created a table in a div only with Json.
The div looks like this:
<div id="datatable" data-mdb-hover="true"
data-mdb-border-color="dark"
data-mdb-full-pagination="true"
data-mdb-clickable-rows="true"
>
</div>
then I create the table:
const columns = [
{label: 'ID', field: 'id'},
{label: 'Role', field: 'role'},
];
const asyncTable = new mdb.Datatable(
document.getElementById('datatable'),
{columns,},
{loading: true}
)
fetch('/api/roles')
.then((response) => response.json())
.then((data) => {
asyncTable.update(
{
rows: data.map((roles) => ({
...roles,
name: `${roles.id}`,
role: `${roles.name}`,
})),
},
{loading: false}
);
});
Now I try to change the class to "active" if I click on a tr like so:
// function to select the row
const table = document.getElementById('datatable');
table.addEventListener('rowClick.mdb.datatable', (e) => {
const selected_item_id = e.row.id
//console.log(e);
//event.target._setClassNames("active");
event.target.querySelector("tbody tr").className = "active"
activeT.push(selected_item_id)
});
It is working but only in the First tr. if I click on the 2nd tr it adds the "active" to the first tr again..
In the browserconsole is this after 2 clicks. Like you can see the double active here:
<tr scope="row" data-mdb-index="0" ><td style="" data-mdb-field="id" false="">18</td><td style="" data-mdb-field="role" false="">Admin</td></tr>
Maybe anyone is able to help me!
CodePudding user response:
Try this
<script>
$('tr').onclick(function (e) {
$(this).toggleClass('active');
})
</script>