Teddu Teddu - 4 months ago 16
Javascript Question

How to apply style on table header only when it is gettinmg clicked and remove style when I click on any other table header?

I have one table which has 7 columns. Below is the HTML code:

<table id="multiple-account-table" cellpadding="0" cellspacing="0">
<thead>
<tr class="border-class">
<th>Employee Name</th>
<th>Account Number</th>
<th>Account Name</th>
<th>Alias</th>
<th>Due Date</th>
<th>Total Due</th>
<th>Payment Amount</th>
</tr>
</thead>
</table>


Now My requirement is, when I click on table header, that particular border should have thick border at the bottom. And when user will click on some other table header then that border should remove from previous table header and apply on currently clicked table header. Something like below image:

Click here to see image

I wrote this jQuery code:

$(document).on('click', 'thead', function () {
$(this).addClass('sort-border');
});


Below is my CSS class for sort-border:

.sort-border {
border-bottom: 4px solid black;
}


It works fine. But when I click on some other table header then previously clicked table header's border doesnt remove. Any suggestion?

Answer

If you first try to remove the class on any header, that should have the class, you will only have one header with the sort-border class.

$(document).on('click', 'th', function () {
    $('th.sort-border').removeClass('sort-border');
    $(this).addClass('sort-border');
});

Also, the thead would give the border to the whole line, if you select the th, it would only be that cell with the border.