Ankur Chachra
Ankur Chachra

Reputation: 131

Change background color of a table row on click

On my webpage, I have a table and I'd like to change the background of a row, and in the process, check the radio button corresponding to that row when the row is clicked. I tried the following using jquery :

<style>
  .active { background-color: #8fc3f7;}
</style>  
<script>
$(document).ready(function() 
  {
    $('#reqtablenew tr').click(function () 
       {
         $('#reqtablenew tr').removeClass("active");
         $(this).addClass("active");
       });
  });
<script>

Any thoughts as to what I might be doing wrong or any workaround would be very welcome. I have included the following scripts in the page. src="http://code.jquery.com/jquery-1.9.1.js"> and src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"

Here's a fiddle of my table http://jsfiddle.net/Gz668/5/

Upvotes: 0

Views: 8237

Answers (3)

null
null

Reputation: 7926

Something like this ... :

$(this).find('input').prop('checked', true);

.. will check the radiobutton of the clicked row.

[Fiddle] (http://jsfiddle.net/McNull/LwT9N/)

Upvotes: 2

Andrew
Andrew

Reputation: 5340

The problem is the td got background color too

.newreqtable td {
   .....
   background-color:#ffffff;

So you need to enforce your active class, e.g.

tr.active td{background-color: #8fc3f7;}

See this: http://jsfiddle.net/Gz668/9/

Upvotes: 2

Rohan Kumar
Rohan Kumar

Reputation: 40639

You forgot to add jquery

Add this in you css

tr.active td {
   background-color: #8fc3f7;
}

I have updated your demo to this

Updated to check the radio try this,

$(this).find('[name="reqradio"]').prop('checked',true);

Full Code

$(document).ready(function () {
    $('#reqtablenew tr').click(function () {
        $('#reqtablenew tr').removeClass("active");
        $(this).addClass("active");
        $(this).find('[name="reqradio"]').prop('checked',true);
    });
});

Demo

Upvotes: 6

Related Questions