Sam Jones Sam Jones - 1 month ago 17
jQuery Question

Edit table with a select box

How can I only show the channel in the table that I pick from the select box?

<select>
<option style="display:none;">Channel</option>
<option value="all">All</option>
<option value="onlineButcher">Online Butcher</option>
<option value="theMeatSite">The Meat Site</option>
<option value="bbqOnline">BBQ Online</option>
<option value="weSellMeat">We Sell Meat</option>
</select>


These are my options so in the table below say I only wanted it to show rows with the channel Online Butcher?

<table class="orders">
<thead>
<tr>
<th>Niche ID</th>
<th>Channel</th>
<th>Customer Name</th>
<th>Dispatch</th>
</tr>
</thead>
<tbody>
<tr>
<td>012345678</td>
<td>Online Butcher</td>
<td>Mr D Jones</td>
<td>Dispatch</td>
</tr>
<tr>
<td>012345677</td>
<td>The Meat Site</td>
<td>Mr C Jones</td>
<td>Dispatch</td>
</tr>
<tr>
<td>012345676</td>
<td>BBQ Online</td>
<td>Mr B Jones</td>
<td>Dispatch</td>
</tr>
<tr>
<td>012345675</td>
<td>We Sell Meat</td>
<td>Mr A Jones</td>
<td>Dispatch</td>
</tr>
</tbody>
</table>


Hope it makes sense.

I used this to sort my table using the headers, maybe something similar but instead of order only show certain channel.

function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}

function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}

window.onload = function () {makeAllSortable();};

Answer

You can retrieve the text of the selected option and then use filter() to find the rows which contain that text and show them. Try this:

$('select').change(function() {
    var value = $('option:selected', this).text(); 
    var $allRows = $('table tbody tr').show();
    var $selectedRows = $allRows.filter(function() {
        return $('td:eq(1)', this).text() == value;
    });

    if ($selectedRows.length) {
        $allRows.hide();
        $selectedRows.show();
    }
}).change();

Example fiddle