morganpdx morganpdx - 4 months ago 9
jQuery Question

filter rows with dropdown using jQuery

I'm having a heck of a time getting this to work. Should be simple, but every route I've tried has not worked. Here's the jQuery I'm using now:

<script type="text/javascript">
$(document).ready(function () {

//filter list by year
$(function () {
$("#ddYear").change(function (evt) {
var year = $("#ddYear").val();

$('tr').show();

$("td[id^='AccessRequestID']").each(function () {
alert("Checking " + this.val);
if ($(this).attr("class") == ".AR_" + year) {
alert("Hiding " + this.val);
$(this).parent().hide();
}
});
});
});
});
</script>


And here's the table I'm trying to filter:

<div class="index-header">Select a Year to View: <%:Html.DropDownList("ddYear", Model.YearList, null %></div>

<table id="arTable">
<tr>
<th>
Year
</th>
<th>
Version
</th>
<th>
Name
</th>

</tr>

<% foreach (var item in Model.AccessRequests) { %>

<tr class="clickable">
<td id="AccessRequestID<%=item.Access_Request_ID%>" class="<%:string.Format("AR_{0}", item.RECORD_YEAR) %>">
<%: Html.DisplayFor(modelItem => item.RECORD_YEAR) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.VERSION_NO) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.EMPLOYEE_NAME) %>
</td>
</tr>

<% } %>

</table>


I initially tried doing something like this:

$("td[id^='AccessRequestID']").parent().hide().filter('.AR_' + year).show();


and while that filtered the rows out great, it didn't unfilter them back in when it should have. So I tried adding
$("td[id^='AccessRequestID']").parent().show;
to reset it first, but that didn't do a thing. (I also tried it with
.each()
, as you can see in my last try). Any advice or help is much appreciated!

Answer

Try this fiddle http://jsfiddle.net/96Evt/ The code is below and I added some demo table rows in the fiddle too.

$("#ddYear").on('change', function () {
        var year = $("#ddYear").val();
        $('tr').show();

        $("td.AR").each(function (index, tdAR) {
            if ($(tdAR).hasClass("AR_" + year)) {
                $(tdAR).parent('tr').hide();
            }
        });
});
Comments