如何用jQuery在Bootstrap 4折叠面板内的表格中搜索并定位内容
Hey there! Let's tackle your problem—searching for a value in a table inside a Bootstrap 4 collapse panel, then automatically expanding the panel and highlighting the matching row. Here's a complete, working solution tailored to your code:
Step 1: Update Your HTML Structure
First, add a search input field so users can type their query. We'll also modify the table rows to include a data-search attribute that holds all searchable content (class, name, roles) for easier matching.
<!-- Add a search input above your accordion --> <div class="mb-3"> <input type="text" id="studentSearch" class="form-control" placeholder="Cerca studente..."> </div> <!-- Your existing collapse panel (modified) --> <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() %} <!-- Add data-search with all searchable fields --> <tr data-search="{{data['class']}} {{data['name']}} {{' '.join(data['roles'])}}"> <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> </div>
Step 2: Add CSS for Highlighting
Add this to your stylesheet to make the matching row stand out clearly:
.highlight-row { background-color: #fff3cd !important; /* Bootstrap warning light color for visibility */ }
Step 3: Implement the Search Logic with JavaScript
We'll use jQuery (since Bootstrap 4 relies on it) to listen for input, search through the rows, expand the panel, and highlight/move to the match.
$(document).ready(function() { $('#studentSearch').on('input', function() { const searchQuery = $(this).val().toLowerCase().trim(); const $collapsePanel = $('#collapseStudents'); let matchFound = false; // Reset all rows to their original state first $('#collapseStudents tbody tr').removeClass('highlight-row').show(); if (searchQuery) { $('#collapseStudents tbody tr').each(function() { const rowContent = $(this).data('search').toLowerCase(); if (rowContent.includes(searchQuery)) { // Expand the collapse panel if it's not already open if (!$collapsePanel.hasClass('show')) { $collapsePanel.collapse('show'); } // Highlight the matching row $(this).addClass('highlight-row'); // Scroll smoothly to center the matching row on screen $(this)[0].scrollIntoView({ behavior: 'smooth', block: 'center' }); matchFound = true; } else { // Hide non-matching rows (remove this line if you want to keep all rows visible) $(this).hide(); } }); } else { // Collapse the panel when search input is cleared (optional, adjust as needed) $collapsePanel.collapse('hide'); } // Optional: Handle no matches scenario if (!matchFound && searchQuery) { $collapsePanel.collapse('show'); // Keep panel open to show empty results state // You could add a "No results found" message here if needed } }); });
Quick Breakdown of How It Works
- Search Input: The input field triggers a search on every keystroke, so results update in real-time.
- Data Attribute: The
data-searchattribute combines all searchable text from each row, making match checks simple and efficient. - Bootstrap Collapse Integration: We use Bootstrap's built-in
collapse('show')method to automatically expand the panel when a match is found. - Highlight & Scroll: Matching rows get a distinct background color, and the page scrolls to center the row for immediate visibility.
- Reset Logic: When the search is cleared, rows reset to their original state, and the panel collapses (you can remove this part if you want the panel to stay open).
内容的提问来源于stack exchange,提问作者alex3025

