Imediava's Blog

Just another WordPress.com site

Selecting a row from a table with JQuery

In this post, I am going to describe how to set up an html table so that the user can select one and only one row from that table. The selection only means that the row selected is going to be highlighted.

First we need to establish with CSS the colour the highlighted row is going to have. In this case we chose red:

tbody tr.hilite td {
    background: none repeat scroll 0 0 red;
}

The last snippet means that all table cells (td) whose parent is a row that belongs to the class hilite will have a red background colour.

Now using JQuery we link the click event for every table row in the page to a function that removes the class hilite for every row first, this way we make sure that there is only going to be one cell highlighted at the same time. Then we add the class to the row that has actually been click.

$(document).ready(function() {
   $('tr').click(function () {
      $(this).siblings('tr').removeClass('hilite');
      $(this).toggleClass('hilite');
   });
}); 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: