ronilondon
ronilondon

Reputation: 25

Add and remove class in table rows JQuery

I have a hierarchal table where I am adding first class name dynamically. I want to add another class (for example – active) when user click a row and remove when click again. If not click again in the same row then it will be remain same (active) and if click into another row, it will add active class there. I do not want to use toggleClass because I already used this in another function. The code I tried, is not working properly.

My table structure is –

<table id="tbl_data">
<tr class="t1" ><td><div><a href="#">test1</a></div></td></tr>
<tr class="t2" ><td><div><a href="#">test2</a></div></td></tr>
<tr class="t3" ><td><div><a href="#">test3</a></div></td></tr>
</table>



var lvl = '@h_lbl'; (eg: cls1)                                  

$('table#tbl_data tbody tr.' + lvl).on('click', function (event) {

if ($(this).hasClass('active'))
    $(this).removeClass('active');
else            
    $(this).addClass('active');
});

Thanks in advance

Upvotes: 2

Views: 4544

Answers (2)

epascarello
epascarello

Reputation: 207501

I would use toggleClass instead of an if/else. In the end it is the same thing under the covers, but it is simpler to maintain.

//Event delegation on the tbody allows for one event to be attached
$("#tbl_data tbody").on("click", "tr", function () {
    //toggle class does the check to add/remove the class
    $(this).toggleClass("selected");
    //If only one row can be selected
    //$(this).siblings(".selected").removeClass("selected");
});
table tr, td { border: 1px solid black; padding: .5em; }
.selected {
    background-color: yellow;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl_data">
<tr class="t1" ><td><div><a href="#">test1</a></div></td></tr>
<tr class="t2" ><td><div><a href="#">test2</a></div></td></tr>
<tr class="t3" ><td><div><a href="#">test3</a></div></td></tr>
</table>

Upvotes: 1

John
John

Reputation: 4981

You can use this :

var table = $('#tble_data');    

table.on('click', 'tr', function () {

    if ( $(this).hasClass('active') ) {
        $(this).removeClass('active');
    }else{
        $(this).addClass('active');
    }

});

Upvotes: 2

Related Questions