Search code examples
javascriptjqueryhtmlbootstrap-4bootstrap-table

Use jQuery to search value in a Bootstrap 4's Table inside a collapse


I'm using Bootstrap 4 table inside a collapse, I want to search for a value in the table and if the value is found, open the collapse and show me the row with the value.

<div id="collapseStudents" class="collapse ml-4" aria-labelledby="headingOne" data-parent="#accordionTypes">
<table class="table table-striped table-borderless">
    <thead>
        <tr>
            <th scope="col" class="text border-bottom">N.</th>
            <th scope="col" class="text border-bottom">Classe</th>
            <th scope="col" class="text border-bottom">Nome e Cognome</th>
            <th scope="col" class="text border-bottom">Ruoli</th>
        </tr>
    </thead>
    <tbody>
        {% for number, data in students_table.items() %}
        <tr>
            <th scope="row" class="text">{{number}}</th>
            <td class="text"><span class="badge badge-secondary">{{data['class']}}</span></td>
            <td class="text">{{data['name']}}</td>
            <td class="text roles" style="width: 30%">
                <span class="badge badge-danger align-text-top ml-1 admin-chip" style="display: {{none if not 'admin' in data['roles'] else block}}; position: relative; top: 2px;">Admin <a class="text-light chip" href=""><i class="fa fa-times" aria-hidden="true" style="position:relative;top:0.3px" data-role="admin" data-user="{{data['name'] + '-' +number}}"></i></a></span>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>


Solution

  • You can try with the following script:

    $('.table tbody').find('tr').each(function(){
      $(this).find('td').each(function(){
        if($(this:contains('valueToSearch'))){
          $('#collapseStudents').collapse();
          // here you can set how to show the row, ex. as bold text
          $(this).text('<b>' + $(this).text() + '</b>');
        }
      });
    });