Thomas
Thomas

Reputation: 5099

Javascript targeting tr element

Im trying to target elements inside of a table with the class '.income_table'. I want to toggle/untoggle a highlighted background color each time a element gets clicked. This isn't working:

<script>
 $(document).ready(function(){
    $(".income_table tr").click(function () {
        $(this).toggleClass("toggled_tr");
     });
 });
</script>

Is there a problem with my code?

Upvotes: 0

Views: 180

Answers (2)

mplungjan
mplungjan

Reputation: 178340

Works for me : http://jsfiddle.net/mplungjan/xBzPW/

<style>
.income_table { background-color:red }
.toggled_tr { background-color:yellow }
</style>
<script>
$(document).ready(function() {
  $(".income_table tr").click(function () {
   $(this).toggleClass("toggled_tr");
  });
});
</script>

<table class="income_table">
    <tr>
        <td>Row 1 cell 1</td>
        <td>Row 1 cell 2</td>
    </tr>
    <tr>
        <td>Row 2 cell 1</td>
        <td>Row 2 cell 2</td>
    </tr>
</table> 

Upvotes: 1

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54810

It looks right, you may need to target the TDs though and apply the class there. Try:

<script>
 $(document).ready(function(){
    $(".income_table tr td").click(function () {
        $(this).siblings().toggleClass("toggled_td");
     });
 });
</script>

Upvotes: 1

Related Questions