svk
svk

Reputation: 4553

How to highlight the selected row in a table using Jquery?

I am having the code like this

When the checkbox is clicked I want to highlight that row.I don't want to use id for a table. Because I am having lot of tables in the same format and I want to apply the css when checkbox is clicked by using single Jquery function.How can I achieve this?

Upvotes: 1

Views: 4092

Answers (3)

JeremyWeir
JeremyWeir

Reputation: 24368

I think you want something like this

$('input[type=checkbox]').click(function(){ 
    var cb = $(this);
    var tr = cb.closest('tr');
    cb.attr('checked') ? tr.addClass('highlight') : tr.removeClass('highlight');
});

css to change the background colors specifically in your example

.highlight .tableeven { background-color: #f00; }
.highlight .tableodd { background-color: #c00; } 

Upvotes: 1

Logan Bailey
Logan Bailey

Reputation: 7127

$(document).ready(function()
{
    $('td input[type="checkbox"]').click(function(){
        if ($(this).is(':checked')){
              $(this).parent().addClass('highlighted');
              $(this).parent().siblings().addClass('highlighted');
        } else if($(this).parent().is('.highlighted')) {
             $(this).parent().removeClass('highlighted');
             $(this).parent().siblings().removeClass('highlighted');
        }
    });
});

There's some different ways to get the row highlighted. But I just added a class called highlighted that had a background color and set it to all the tds

Upvotes: 3

sTodorov
sTodorov

Reputation: 5461

Perhaps this :

$('table input[type=checkbox]').click(function(){
if($(this).is(':checked'))
$(this).parents('tr :first').addClass('myStyleClass');
else
$(this).parents('tr :first').removeClass('myStyleClass');
});

Upvotes: 0

Related Questions