santa
santa

Reputation: 12512

Hiding all but first table row with jQuery

I have a table with a drop-down html selector in the first row. The first option is blank.

I need to hide all rows in the table except the ones that match selector value. If the first option is selected -- hide all rows below. The reason i used class for TRs, because there could be multiple rows for some matched options.

JS

$("#mySelector").change(function(){
    opt = $(this).val();
    if(opt != "") {
        $("." + opt).show();
    } else {
        $("#myTbl tr:not(first-child)").hide(); 
    }
});

HTML

<table id="myTbl">
<tr>
   <td>
    <select id="mySelector">
    <option> select one
    <option value="val1"> v1
    <option value="val2"> v12
    <option value="val3"> v3
    </selector>
   </td>
</tr>
<tr class="val1">
   <td>
    asdasd 1
   </td>
</tr>

<tr class="val2">
   <td>
    asdasd 2
   </td>
</tr>

<tr class="val3">
   <td>
    asdasd 3
   </td>
</tr>
</table>

It seems like it should work, but it doesn't. What am I missing?

Upvotes: 3

Views: 7973

Answers (4)

rashid choudhary
rashid choudhary

Reputation: 11

$('#tableBody tr:gt(0)').hide();

Upvotes: 0

gdoron
gdoron

Reputation: 150313

$("#myTbl tr:not(:eq(0))").hide(); 

Or:

$("#myTbl tr:not(:first)").hide(); 

You need to add a value attribute to the first <option>:

<select id="mySelector">
<option value=""> select one // <<<<======
<option value="val1"> v1
<option value="val2"> v12
<option value="val3"> v3
</select> // Not </selector>

Live DEMO


Note that opt = $(this).val();
should be this.value nice, clear, clean and faster.

Upvotes: 3

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79860

Try something like below,

$("#mySelector").change(function(){
    var opt = $(this).val();
    if(opt != "") {
        $("." + opt).show();
    } else {
        $("#myTbl tr:gt(0)").hide(); 
    }
});

Upvotes: 3

Kevin B
Kevin B

Reputation: 95054

You missed the : before first-child

$("#myTbl tr:not(:first-child)").hide(); 

Upvotes: 8

Related Questions