Reputation: 325
I have a table like this:
I want to change the background color of the cells with the prices when i click on them (such as addClass(on)
), as you can see on the bottom-left corner, and also change the background color of the other cells too (such as addClass(off)
).
I don't want the other cells being effected (the ones with text and also different colors).
I also need to get the id of the row which the clicked cell belongs.
Here is the structure of a row.
<tr class="taksit" id="tek">
<td><b>Tek Çekim</b></td>
<td><?=$sontutar?> TL</td>
<td><?=$sontutar?> TL</td>
<td><?=$sontutar?> TL</td>
<td><?=$sontutar?> TL</td>
<td><?=$sontutar?> TL</td>
<td><?=$sontutar?> TL</td>
<td><?=$sontutar?> TL</td>
</tr>
I have tried a few tricks found on here, but not able to do it. Any idea how can I do this?
Upvotes: 1
Views: 1089
Reputation: 47976
$("#table_selector td.clickable").on('click',function(){
// cache $(this)
var clickedElement = $(this);
// remove background color from other clickable items
$("td.clickable").css('background','none');
// change the background color of the clicked <td>
clickedElement.css('background','red');
var rowId = clickedElement.closest('tr').attr('id');
});
Let me explain a little bit about what I have done here.
First of all, you said that you don't want every <td>
to be affected by these clicks and background changes. So you should give a class to all the <td>
's that are "clickable" and then you can limit your on('click')
event to the elements you want. You could ofcourse also do the opposite, adding a "noClick" class to the ones you want to ignore...
Changing the background color of the <td>
can be done in a few ways, I've chosen for the sake of example to use the simple .css('background','red');
, but I'm sure you have some more logic in your actual code.
The rowId
is extracted by looking for the closest parent element that is a <tr>
using the closest()
function. Then simply looking at the id
attribute.
Upvotes: 1
Reputation: 92913
$('table#uniqueID tbody td').on('click',function() {
$(this).closest('tbody').find('td').removeClass('highlight');
$(this).addClass('highlight');
});
Upvotes: 1