Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I toggle a table row background color for Twitter Bootstrap?

In reference to my earlier post:

My HTML

<table class="table table-bordered table-condensed table-striped">
    <thead>
        <tr>
            <th>Col 1</th>
            <th>Col 2</th>
            <th>Col 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><strong>Data 1</strong></td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>
        <tr>
            <td><strong>Data 1</strong></td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>
        <tr>
            <td><strong>Data 1</strong></td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>
    </tbody>
</table>

jQuery

$(document).ready(function(){
    $('table.table-striped tr').on('click', function () {
        $(this).find('td').css('background-color', '#ff0000');

         // toggleClass doesn't seem to work

     });
 });

I'm trying to toggle the row color off an on via my click event. Any idea if this is possible using a user defined css selector?

like image 243
user1216398 Avatar asked Sep 27 '12 17:09

user1216398


1 Answers

You may try this

CSS

.bg{background-color:#ff0000 !important;}​

JS

$(document).ready(function(){
    $('table.table-striped tbody tr').on('click', function () {
        $(this).closest('table').find('td').removeClass('bg');
        $(this).find('td').addClass('bg');
    });
});​

DEMO.

Update: For toggling

$(document).ready(function(){
    $('table.table-striped tbody tr').on('click', function () {
        $(this).find('td').toggleClass('bg');
    });
});​

DEMO.

like image 172
The Alpha Avatar answered Nov 15 '22 05:11

The Alpha