I need to filter through rows of a table using a drop-down box with jQuery. What I can't figure out how to do is how to relate the value of the options to the data-type of the table rows.
HTML:
<label for="filter">Type:</label>
<select id="filter>
<option value="all">All Steps</option>
<option value="standard">Standards</option>
<option value="review">Reviews</option>
</select>
<table id="table>
<tr id="one" class="row" data-type="standard">
<td>Standard</td>
</tr>
<tr id="one" class="row" data-type="review">
<td>Reviews</td>
</tr>
</table>
JS:
$("#filter").change(function () {
$("#table").find(data-type).each(function () {
if ($(this).text() != $("#filter").val())
$(this).hide();
else
$(this).parent().show();
if ($("#filter").val() == "all")
$(this).show();
});
});
The jQuery here is just pieced together based off of what I've found so far by researching around. It's important that I leave the data-type attribute in the table rows.
I'm pretty new to jQuery, so anything helps!
Here's the Code Pen: http://codepen.io/aburnsworth/pen/XKzgqa?editors=1111
You find you what value is selected by using .val();
You get all the rows you need that .val()
to match against $('.row');
Loop all the rows when you find a match hide all, only then show what you want, b/c computer do this so fast seems instant
.each(function(index, element) {});
Now you have a filter
EDIT: just move the hide all outside of the loop should do it.
$(".filter").change(function() {
var filterValue = $(this).val();
var row = $('.row');
row.hide()
row.each(function(i, el) {
if($(el).attr('data-type') == filterValue) {
$(el).show();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label for="filter">Type:</label>
<select class="filter" data-tableId="table1">
<option value="all">All Steps</option>
<option value="standard">Standards</option>
<option value="review">Reviews</option>
<option value="inspection">Inspections</option> <option value="payment">Payments</option>
<option value="document">Documents</option>
</select>
<table id="table1">
<tr id="one" class="row" data-type="standard">
<td>Standard</td>
</tr>
<tr id="two" class="row" data-type="review">
<td>Review</td>
</tr>
<tr id="three" class="row" data-type="inspection">
<td>Inspections</td>
</tr>
<tr id="four" class="row" data-type="payment">
<td>Payments</td>
</tr>
<tr id="five" class="row" data-type="document">
<td>Documents</td>
</tr>
<tr id="one" class="row" data-type="standard">
<td>Standard</td>
</tr>
<tr id="two" class="row" data-type="review">
<td>Review</td>
</tr>
<tr id="three" class="row" data-type="inspection">
<td>Inspections</td>
</tr>
<tr id="four" class="row" data-type="payment">
<td>Payments</td>
</tr>
<tr id="five" class="row" data-type="document">
<td>Documents</td>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With