necrofish666 necrofish666 - 4 months ago 6
HTML Question

How do I select all elements of a specific class name?

I have a table within which I want a user to be able to click on any table row, and when they do, it will change the background color of that table row to show that it is highlighted, that's the one that has been selected. I also want them to be able to be able to then select a different table row within that same table, which then should remove the background color from the previous row, and change the newly selected table row to the highlight background color.

So I have

<tr class="clientRow">
<td>
@Html.DisplayFor(x => x.ReferralTypeDescription)
</td>
<td>
@Html.DisplayFor(x => x.ReferralDate)
</td>
<td>
@Html.DisplayFor(x => x.ReferralStatus)
</td>
<td>
@Html.DisplayFor(x => x.ContactNo)
</td>
</tr>

<tr class="clientRow">
<td>
@Html.DisplayFor(x => x.ReferralTypeDescription)
</td>
<td>
@Html.DisplayFor(x => x.ReferralDate)
</td>
<td>
@Html.DisplayFor(x => x.ReferralStatus)
</td>
<td>
@Html.DisplayFor(x => x.ContactNo)
</td>
</tr>


I would imagine I would have a CSS class like
isSelected
or something similar, which would be added to the clicked row, and removed from the previous row that has that class. I'm just not sure how to do it. Anyone able to help?

Answer

You idea is correct. You can implement it like following.

$('.clientRow').click(function(){
    $('.clientRow.isSelected').removeClass('isSelected');
    $(this).addClass('isSelected');  
});
.isSelected {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
    <tr class="clientRow">
        <td>
            Referral Type Description
        </td>
        <td>
            Referral Date
        </td>
    </tr>
    <tr class="clientRow">
        <td>
            Referral Type Description
        </td>
        <td>
            Referral Date
        </td>
    </tr>
</table>

Comments