Search code examples
jquerytwitter-bootstrap-3addclassbootstrap-table

Add a css class to tr fails


I am using Bootstrap Table where I load my data remotly with data-url="data.json". So my table:

<table id="mytable" class="table table-hover" data-url="data.json" data-toggle="table" id="table-pagination"  data-pagination="true">
    <thead>
         <tr>
              <th data-field="id" data-align="center">id</th>
              <th data-field="type" data-align="center">type</th>
              <th data-field="name" data-align="center">name</th>
              <th data-field="product" data-align="center">product</th>
              <th data-field="use" data-align="center">use</th>
              <th data-field="quantity" data-sortable="true">quantity</th> 
         </tr>
    </thead>
</table>

where tha last column has numbers only (without any other characters). The data.json is like this:

[
    {
        "id": 120,
        "type": "type1",
        "name": "name 1",
        "product": "250304-01",
        "use": "use 1",
        "quantity": 10000
    },
    {
        "id": 121,
        "type": "type2",
        "description": "name 2",
        "product": "250124-01",
        "cutter": "use 1",
        "quantity": 80
    }
]

I want to check, when the value in the last column is smaller than 100 then a class to be added in that tr. I searched about it and I found that this can be done with filter. So, I code this:

 $('tbody tr').filter( function(){
                       return $('td:last', this).text() < 100;
                     }).addClass('warning');

I save the above as it is to a file addWarning.js and I put it at the bottom of my page in the end of all the other scripts.

 <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
 <script src="assets/js/bootstrap.min.js"></script>
 <script src="assets/js/bootstrap-table.js"></script>
 <script src="assets/js/bootstrap-table-el-GR.js"></script>
 <script src="assets/js/addWarning.js"></script>

But it isn't working.. What am I missing?


Solution

  • Filter the table row only after remote content is loaded, otherwise $('tbody tr') will not select any element. So you can bind event handler for load-success.bs.table event , it fires when remote data is loaded successfully.

    $('table').on('load-success.bs.table', function() {
      $('tbody tr').filter(function() {
        return $('td:last', this).text() < 100;
      }).addClass('warning');
    });