birchy
birchy

Reputation: 519

change background color of table row clicked

I am trying to highlight the row of the last item clicked. Tried some jquery code found in searches and none of it even tries to work. Must be doing something basic wrong. Here's a jsfiddle with one solution tried: http://jsfiddle.net/birchy/he9ts/1/

<table>
<tr>
<td>====></td>
<td class='msgRow' onclick='loadMsg();'>Content1</td>
</tr>
<tr>
<td>====></td>
<td class='msgRow' onclick='loadMsg();'>Content2</td>
</tr>
<tr>
<td>====></td>
<td class='msgRow' onclick='loadMsg();'>Content3</td>
</tr>
<tr>
<td>====></td>
<td class='msgRow' onclick='loadMsg();'>Content4</td>
</tr>
</table>

function loadMsg()
{
alert('row clicked');
$(this).closest("tr").css('background-color','green');
$(this).css('background-color','red');  
}

Upvotes: 0

Views: 5974

Answers (2)

Wilfredo P
Wilfredo P

Reputation: 4076

Only you need is pass this on the onclick on each td to get wich td has been clicked:

<tr>
    <td>====></td>
    <td class='msgRow' onclick='loadMsg(this);'>Content3</td>
</tr>

And you Js will be:

function loadMsg(e)
{
    alert(e);
    $(e).closest("tr").css('background-color','green');
    $(e).css('background-color','red'); 
}

Live Demo

Another way only Jquery (Recomended):

$(document).ready(function(){
    $('.msgRow').on('click', function(){
        $(this).closest("tr").css('background-color','green');
        $(this).css('background-color','red');  
    });
});

and removing the onclik in all td.

Upvotes: 2

droymanz
droymanz

Reputation: 343

Try this one

First, pass the element clicked on your function by using this only

<tr>
    <td>===></td>
    <td class="msgRow" onclick="onclick(this)">Content 3</td>
</tr>

Then on your js

function loadMsg(e){
    // remove first the background applied on all tr
    $('.msgRow').closest('tr').css('background-color','none'); 

    // remove also the background applied on all 'msgRow' classes
    $('.msgRow').css('background-color','none');

    // then you can now change the background color of the clicked row and cell
    $(e).closest('tr').css('background-color','green');
    $(e).css('background-color','red');
}

DEMO

Upvotes: 1

Related Questions