Abdel Raoof Olakara
Abdel Raoof Olakara

Reputation: 19353

Selecting rows in Tablesorter

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

Upvotes: 3

Views: 6140

Answers (5)

Eric P
Eric P

Reputation: 598

To enable select and deselect toggling via jQuery's toggleClass:

$(document).ready( function() {
    /* jQuery v1.11.1 */
    $( "table.tablesorter tbody tr" ).click(function() {
      $( this ).toggleClass( "selected" );
    });
});

/* CSS for hover row & select/lock the row with color */
table.tablesorter tbody tr:hover td {
    background-color: #f4f5f6;
}
table.tablesorter tbody tr.selected td {
    background-color: #f4f5f6;
}

Upvotes: 4

user187183
user187183

Reputation:

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.

Upvotes: 0

EmKay
EmKay

Reputation: 1089

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

Upvotes: 0

Alex Barrett
Alex Barrett

Reputation: 16455

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');
});

Upvotes: 1

easement
easement

Reputation: 6139

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');

 });

Upvotes: 1

Related Questions