craighandley
craighandley

Reputation: 156

How to change a table row color when clicked and back to what it was originally when another row clicked?

As the title explains, I wish to change the color of a row when it is clicked then revert the color when another is clicked, however still change the color of the newly clicked row.

A resolution in JQuery would be much appreciated. I just can't crack this one. What I have so far but it's not working for me.

function loadjob(jobIDincoming, currentID){
$("#joblistingDetail").load('jobview.php' , {jobID: jobIDincoming}).hide().fadeIn('100');
var last = new Array();
last.push(currentID);
$(last[last.length-1]).closest('tr').css('background-color', 'white');
$(currentID).closest('tr').css('background-color', 'red');};

Upvotes: 1

Views: 6051

Answers (4)

Greg
Greg

Reputation: 31378

I would use

$(document).on('click', 'tr', function(e){
    // reset rows
    $('tr').css('background-color', 'white');
    // set colour of row raising the click event 
    $(this).css('background-color', 'red');
});

Also I would use $.on as its cool...read up on why it is!

Upvotes: 1

Rafay
Rafay

Reputation: 31043

you haven't shown the marup so

$(document).delegate("tr","click",function(e){
  $("tr").css('background-color', 'white');
  $(this).css('background-color', 'red');
});

DEMO

Upvotes: 1

PraveenVenu
PraveenVenu

Reputation: 8337

ou can use a class, like this:

.selected td { background-color: #CCC; }

Then apply it when clicked using .delegate(), like this:

$("#tab1").delegate("tr", "click", function() {
   $(this).addClass("selected").siblings().removeClass("selected");
});

http://jsfiddle.net/nick_craver/Ymd65/

Upvotes: 0

Starx
Starx

Reputation: 78991

No need to complicate things. This is as simple as possible.

$("table tr").click(function() {
   $("table tr").css("background", "#fff"); //reset to original color
   $(this).css("background", "#fo0"); //apply the new color
});

Upvotes: 1

Related Questions