Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tr background-color

Tags:

jquery

css

I have something like this:

<tr id='<%=currentRow %>' onclick="SetBackgroundColor(this)" style="background-color:Yellow">

When i click on a row i want to change its background color and i did like this:

function SetBackgroundColor(rowId) 
{
     $(rowId).css("background-color", "#000000");
}

but i don't know why it doesn't work. Any suggestions please?

like image 648
user158625 Avatar asked Nov 30 '09 17:11

user158625


People also ask

How do I change the background color in HTML TR?

The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5. Attribute Values: color_name: It sets the background color by using the color name.

Can TR have background color?

Setting the Background Color of Table Rows. The bgcolor attribute is now deprecated, but it was once the correct way to control the background color of table rows. Color names (such as “blue”), hex numbers, and rgb color codes could all be used with the bgcolor attribute.

How do I change the background color of a table in CSS?

What to Know. Easiest: add the style property background-color to the table, row, or cell tag. Next easiest: use the attribute bgcolor.


4 Answers

IE has a problem with background colors for the TR element. A more safe way is to set background to the TD's and TH's inside the TR:

<table id="tabletest">
    <tr>
        <td>testcell</td>
    </tr>
</table>

<script>
$('#tabletest tr').bind('click', function(e) {
    $(e.currentTarget).children('td, th').css('background-color','#000');
})
</script>

Added: you can assign a single event handler for the entire table to increase performance:

$('#tabletest').bind('click', function(e) {
    $(e.target).closest('tr').children('td,th').css('background-color','#000');
});
like image 92
David Hellsing Avatar answered Sep 29 '22 18:09

David Hellsing


In jQuery you do not have to use the onclick attribute to assign an event handler. Lets say you add a class called mytr to each tr that you want to affect. Then you can do something like this:

 $(document).ready(function(){
        $(".mytr").click(function(){
             $(this).css("background-color", "#000000");
        });
 });

And that will apply the event handler to all rows with the class mytr.

like image 42
Vincent Ramdhanie Avatar answered Sep 29 '22 17:09

Vincent Ramdhanie


This will reset each row upon clicking a new one...

$(document).ready(function(){

  $('tr').click(function(){
    $('tr td').css({ 'background-color' : 'green'});
    $('td', this).css({ 'background-color' : 'red' });
  }); 

});

demo: http://jsbin.com/aciqi/

like image 42
luckykind Avatar answered Sep 29 '22 17:09

luckykind


 $('#RowID').children('td, th').css('background-color','yellow');
like image 41
Raj Avatar answered Sep 29 '22 18:09

Raj