Filter html table using column dropdown by jQuery
I have a jQuery script that filters an html table with many columns, I just need to show all rows based on user input, but only want to filter the table through a specific column selected by the user from the dropdown
JQuery code
$(document).ready(function(){
$("#kwd_search").keyup(function(){
var term=$(this).val()
if( term != "")
{
$("#my-table tbody>tr").hide();
$("#my-table td").filter(function(){
return $(this).text().toLowerCase().indexOf(term ) >-1
}).parent("tr").show();
$("#my-table tbody>tr th").show();
}
else
{
$("#my-table tbody>tr").show();
}
});
});
HTML code
<select id="clmn_name">
<option>Column 1</option>
<option>Column 2</option>
<option>Column 3</option>
</select>
<input id="kwd_search" placeholder="Search Me">
<table id="my-table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Mango</td>
</tr>
<tr>
<td>Strawberry</td>
<td>Banana</td>
<td>Cherry</td>
</tr>
</tbody>
</table>
So how can you filter the returned HTML according to the user-selected table column?
+3
source to share
1 answer
You can use the property selectedIndex
of the select element to filter the target cells:
$("#kwd_search").keyup(function () {
var index = $('#clmn_name').prop('selectedIndex'),
term = $.trim(this.value);
if (term.length === 0) {
$("#my-table tbody > tr").show();
return;
}
$("#my-table tbody > tr").hide().filter(function () {
return this.cells[index].textContent.toLowerCase().indexOf(term) > -1;
}).show();
});
If you want to listen for the change event of a select element:
$(document).ready(function () {
// Caching the elements and binding handlers
var $s = $('#clmn_name').on('change', filterRows),
$i = $("#kwd_search").on('keyup', filterRows),
$rows = $("#my-table tbody > tr");
function filterRows() {
var ind = $s.prop('selectedIndex'),
term = $.trim($i.val().toLowerCase());
if (term.length === 0) return $rows.show();
$rows.hide().filter(function () {
return this.cells[ind].textContent.toLowerCase().indexOf(term) > -1;
}).show();
};
});
jQuerish's way of selecting target cells would be:
return $('td', this).eq(index).text().toLowerCase().indexOf(term) > -1;
+1
source to share