lodkkx
lodkkx

Reputation: 1173

Making table rows but not table headers clickable in jquery

Currently I am using

$('#mytable tr').click(function() {
    blah blah
});

This makes all rows, including the headers clickable. How can I exclude the headers or <th>'s?

Upvotes: 3

Views: 2753

Answers (4)

David Thomas
David Thomas

Reputation: 253308

The easiest way, assuming you've marked your table up accurately, is to use:

 $('#mytable tbody tr').click(function() {
     blah blah
 });

Failing that:

 $('#mytable tr').filter(
     function(){
         return $(this).find('td').length;
     }).click(function() {
     $(this).addClass('clicked');
 });

JS Fiddle demo.

Upvotes: 1

Olegas
Olegas

Reputation: 10507

Separate you header and body using <thead> and <tbody> tags, and change your selector to "#mytable tbody tr"

HTML will look something like this

<table> 
    <thead>
        <tr>
         ...
        </tr>
    </thead>
    <tbody>
         <tr>
            ...
         </tr>
    </tbody>
</table>

Upvotes: 8

Sudesh
Sudesh

Reputation: 1169

Use Jquery delegate

$("#mytable").delegate("td", "click", function() {
  //Do something
});

this should work

Upvotes: 0

gdoron
gdoron

Reputation: 150253

You can remove them with the not function:

$('#mytable tr').not('th').click(function() {
   blah blah
});

Or:

$('#mytable tr:not(th)').click(function() {
   blah blah
});

Upvotes: 0

Related Questions