Filtra columnas en una tabla
Filtra las columnas de una tabla sin necesidad de un plugin ni datatables
by eorozco
HTML
<body>
<strong>Filtra una tabla sin necesidad de plugins ni datatables, solo con jquery </strong>
<table cellpadding="3" cellspacing="1" border="1">
<thead>
<tr>
<th>First Name:
<input type="text" name="filterfname" value="">
</th>
<th>Last Name:
<input type="text" name="filterlname" value="">
</th>
<th>City:
<input type="text" name="filtercity" value="">
</th>
<th>State:
<input type="text" name="filterstate" value="">
</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>aBcd</td>
<td>efg</td>
<td>ahij
<td>
</tr>
<tr>
<td>al</td>
<td>abc</td>
<td>op</td>
<td>qr
<td>
</tr>
<tr>
<td>6a</td>
<td>2</td>
<td>st</td>
<td>yz
<td>
</tr>
<tr>
<td>6</td>
<td>2</td>
<td>3</td>
<td>4
<td>
</tr>
</tbody>
CSS
visible {
background-color:white;
}
table tbody tr:nth-child(even) {
background-color:grey;
}
JavaScript
$(document).ready(function () {
$('tbody tr').addClass('visible');
$('thead tr th input:text').keyup(function (event) {
if (event.keyCode == 27 || $(this).val() == '') {
$('tbody tr td ').show();
} else {
for (var i = 1; i < 10; i++) {
if ($("thead tr th:nth-child(" + i + ") input:text").val().length > 0) {
var fn = filter("tbody>tr > :nth-child(" + i + ")", $(this).val());
}
}
}
});
});
function filter(selector, query) {
var z = null;
query = $.trim(query);
query = query.replace(/ /gi, '|');
$(selector).each(function () {
if ($(this).text().search(new RegExp(query, "i")) < 0) {
$(this).siblings().hide();
$(this).hide();
} else {
$(this).siblings().show();
$(this).show();
}
});
}