Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Highlight/De-highlight table row on click

Tags:

jquery

I want my script to highlight the row that I select and it works great, but when a row is selected/highlighted i want it to be "deselected/dehighlighted" if another row is selected. How do i do this?

Here is current code for selecting a row, it deselects, but only if i click on the same row again:

$(".candidateNameTD").click(function() {
            $(this).parents("tr").toggleClass("diffColor", this.clicked);
        });

Html table

<table id="newCandidatesTable">
    <thead>
        <tr>
            <th style="cursor: pointer;">ID</th>
            <th style="cursor: pointer;">Navn</th>
            <th style="cursor: pointer;">Email</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    <% foreach (var candidate in Model.Ansogninger)
    {
         %>
            <tr id="<%= candidate.AnsogerID %>" class="newCandidatesTableTr">
                <td><div id="candidateID"><%= candidate.AnsogerID %></div></td>
                <td><div id="<%= "candidateName_" + candidate.AnsogerID %>" class="candidateNameTD"><%= candidate.Navn %></div></td>
                <td><div id="candidateEmail"><%= candidate.Email %></div></td>
                <td>
                    <div id="<%= "acceptCandidateButton_" + candidate.AnsogerID %>" class="acceptb" style="cursor: pointer; border: 1px solid black; width: 150px; text-align: center;">Godkend</div>
                </td>
            </tr>
         <%
    } %>
    </tbody>
    </table>
like image 427
Poku Avatar asked Aug 17 '09 12:08

Poku


People also ask

How do I change the selected HTML table row background color using jquery?

Change the 'background-color' property of the row in the click event handler of the row. Code would be: //attach an onclick event handler to the table rows $(“#myTable tbody tr”). click(function(){ //change the 'background-color' property to the desired color.


3 Answers

You could first deselect all rows, like

    $(".candidateNameTD").click(function() {
        $(this).closest("tr").siblings().removeClass("diffColor");
        $(this).parents("tr").toggleClass("diffColor", this.clicked);
    });

edit: yep, sry, but the idea was right ;)

like image 170
fresskoma Avatar answered Oct 10 '22 19:10

fresskoma


$(".candidateNameTD").click(function() {
            $("tr").removeClass("diffColor");
            $(this).parents("tr").addClass("diffColor");
        });
like image 26
Daniel Moura Avatar answered Oct 10 '22 21:10

Daniel Moura


This will only affect the current table:

$(".candidateNameTD").click(function() {
    $('table#newCandidatesTable tr').removeClass("diffColor");
    $(this).parents("tr").addClass("diffColor");
});
like image 29
karim79 Avatar answered Oct 10 '22 20:10

karim79