tags:

views:

48

answers:

2

my table has the following html

<table class="tb" id="tb1">
<tr>
<th scope="col">OrderID</th>
<th scope="col">ProductName</th>
<th scope="col">Quantity</th>
</tr>
<tr>....</tr>

When i click only on either OrderID, ProductName or Quantity i.e heading, I want to apply a css class to entire column.

A: 

Bind to the click event on the th elements, find the index of clicked th and add a class to the corresponding col element.

Working demo: http://jsbin.com/iraco (Editable via http://jsbin.com/iraco/edit)

Pertinent code:

<table id="eggs">
  <col /> <col /> <col />
  <tr> <th>foo</th> <th>bar</th> <th>baz</th> </tr>
  <tr> <td>foo1</td> <td>bar1</td> <td>baz1</td> </tr>
  <tr> <td>foo2</td> <td>bar2</td> <td>baz2</td> </tr>
  <tr> <td>foo3</td> <td>bar3</td> <td>baz3</td> </tr>
</table>
<script>
  $('#eggs th').click(function(){
    var index = $(this).prevAll().length;
    $('#eggs col')
      .removeClass('clicked')
      .eq(index).addClass('clicked');
  });
</script>
brianpeiris
thank you for the answer
Satya
A: 
$(document).ready(function(){
    $("table#tb1 th").click(function(){
        //from question#788225
        var col = $(this).parent().children().index($(this)) + 1;
        var t = $("table#tbl");
        $("td",t).removeClass("selCol");
        $("table#tbl tr td:nth-child("+ col  +")").addClass("selCol");
    });
});
TheVillageIdiot
FYI This code is at least an order of magnitude slower than my code, especially for large tables: http://jsbin.com/eriyi
brianpeiris