squirc77
squirc77

Reputation: 73

Show/ Hide table rows based on dropdown selection

I have a date selector for years 2012 & 2013. Based on the selection I want to display only rows with certain classes. Can someone please show me where I am going wrong?

jQuery

<script>
$(document).ready(function() {
$(".yr12 td").hide();

$('#selectYr').change(function () {
    var val = $(this).val();
    if (val == yr12) {
         $('.yr12 td').show();
         $('.yr13 td').hide();
    } else {
        $('.yr12 td').hide();
         $('.yr13 td').show();
    }
    });
});

html

<select id="selectYr">
    <option value="yr13">2013</option>
     <option value="yr12">2012</option>
   </select>
<br><br>

<table>
<tr>
<th>Date</th>
<th>Description</th>
</tr>
<tr class="yr13">
<td>February 2013 </td>
<td>Description 1</td>
</tr>
<tr>
<td class="yr13">January 2013</td>
<td>Description 2</td>
</tr>
<tr class="yr12">
<td>November 2012</td>
<td>Description 3</td>
</tr>
<tr class="yr12">
<td>December 2012</td>
<td>Description 4</td>
</tr>
</table>

Upvotes: 1

Views: 10940

Answers (3)

arun
arun

Reputation: 91

two things..

1 ->

 <tr>
<td class="yr13">January 2013</td>

should be

<tr class="yr13">
<td>January 2013</td>

2-->

if (val == "yr12") {

Upvotes: 1

MikeB
MikeB

Reputation: 2452

You are trying to compare val to another variable called yr12 instead of comparing to the value 'yr 12'

Here is the correct code:

$(document).ready(function() {
                $(".yr12 td").hide();

                $('#selectYr').change(function () {
                    var val = $(this).val();
                    if (val == 'yr12') {
                         $('.yr12 td').show();
                         $('.yr13 td').hide();
                    } else {
                        $('.yr12 td').hide();
                         $('.yr13 td').show();
                    }
                    });
                });

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219936

You're missing the quotes around your string:

if (val == 'yr12') { }
//         ^    ^

Upvotes: 5

Related Questions