views:

316

answers:

4

Hi all,

I user Tablesorter a jQuery plugin (I am sure other know about it) in my project. I need to add a feature where in when users click on a row, it gets selected . I tried the following code but, its not working out.

$('#myTable tr').click(function(event) {
  $(this).addClass('selected');

 });

Could anybody tell me the best way to do it? Is there any plug-in already for this?

Thanks in advance,
Abdel Olakara

+1  A: 

That looks correct to me. Do you have a CSS class defined for tr.selected?

Maybe when you are clicking, you hit the td element and not the tr. Maybe you need to use the parent:

http://docs.jquery.com/Traversing/parent

something like this (untested):

$('#myTable td').click(function(event) {
         $(this).parent("tr").addClass('selected');

 });
easement
I have tr.selected.. here is my code:tr.selected{background: red;}But when i run my code or yours, there is no effect on display!! The CSS do get applied on the tr.
Abdel Olakara
A: 

What you have appears correct. Are you executing it after the document is ready?

$(function() {
    $('#myTable tr').click(function() {
         $(this).addClass('selected');
    });
});

Alternatively, you could use live events.

$('#myTable tr').live('click', function() {
     $(this).addClass('selected');
});
Alex Barrett
A: 

I think that Tablesorter recreates the whole table so that could be why there is no change as it "destroys" the click event attached to the tr. You should try it using a live event and see if that works: Documentation for live events at jQuery.com

EmKay
A: 

Your click event seems to work just fine on my table, I'm just wondering how you would unselect by clicking again? tying a variable to whether is is selected seems like an easy solution, but how would I do that?

Pardon my answering your question with another question and my newness to JS.

Chris