I have a bootstrap table that looks like this -
$('#colorChangeForm').submit(function () {
changeBackground();
return false;
});
function changeBackground() {
var noOfProposals = document.getElementById("countInput").value;
var table = document.getElementById("myTable");
var tableLen = table.rows.length;
for (var i = 1; i < tableLen; i++) {
if (noOfProposals) {
if (table.rows[i].cells[1].innerText > noOfProposals) {
table.rows[i].cells[1].className = 'table-danger';
}
else {
table.rows[i].cells[1].className = 'table-success';
}
}
}
}
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="//code.jquery.com/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.js" integrity="sha256-o8aByMEvaNTcBsw94EfRLbBrJBI+c3mjna/j4LrfyJ8=" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
</head>
<form class="form-inline" id="colorChangeForm">
<div class="form-group mb-2">
<label for="countInput">No. of Proposals - </label>
<input type="proposals" class="form-control" id="countInput" placeholder="limit of proposals">
</div>
<button type="submit" class="btn btn-primary mb-2" id="btnChangeColor">Submit</button>
</form>
<table data-toggle="table"
data-classes="table table-hover"
data-striped="true"
data-sort-order="asc"
style="width: auto;" id="myTable" class="table">
<thead class="thead-dark">
<tr style="background-color:lightgray">
<th data-sortable="true">Name</th>
<th data-sortable="true">Total Proposals</th>
</tr>
</thead>
<tr>
<td>A</td>
<td>123</td>
</tr>
<tr>
<td>B</td>
<td>150</td>
</tr>
<tr>
<td>C</td>
<td>170</td>
</tr>
</table>
I'm changing the class for "Total proposals" based on the value. This value, I'm getting from a form on the same page.
I'm executing a javascript where I'm changing the color of the cell
This changes the color of the cell correctly.
However, When I sort the table (not refresh the page), it somehow removes the dynamic cell class. Any Idea how to keep my cell class while sorting the table?
The sorting event is handled by the bootstrap-table extension you are using in your code. It's not part of bootstrap itself and it's sorting system works by recreating table rows in the selected order. That means that you are assigning a class to an element that will be deleted. To solve the problem you can:
Use a different sorting system that dosn't delete column rows
Execute the changeBackground
function again after the sortying is ended