ronilondon ronilondon - 3 months ago 12
Javascript Question

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

Answer

You can use this :

var table = $('#tble_data');    

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

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

});
Comments