Reputation: 10342
I have to change the table row color based on some business logic. I have limited access. I have PHP code which decide TD content...from that TD I have to change the current TR background color.
jQuery can help, as it is having lot of traverser and accesser.
code I am writing is
<script type="text/javascript">$(this).closest("td").css("border", "1px solid red");</script>
But not able to access the current TD or TR
Upvotes: 0
Views: 1190
Reputation: 12693
Instead of using this, give the element an id and get it using jQuery. In your code, this points to nothing. like:
<table><tr><td> <input id="myInput" type="text" /> </td></tr></table>
//If you want to access the td
$('#myInput').closest("td").css("border", "1px solid red");
//If you want to access the tr
$('#myInput').closest("tr").css("background", "red");
Upvotes: 2
Reputation: 1614
You need some way to target the TD content or the TD itself. If the content was unique you could search for a keyword or phrase. Either way, you need a selector - $(this) is just a reference to the jquery object once inside a handler.
EDIT
I thought about it a bit more and here's something you could try. Since you only have access to the content, could you add something to it like UPDATED? If so, then you could add that keyword and with jQuery we can add in the border, background and remove the keyword like this:
<table cellpadding="5px" cellspacing="5px" border="1px">
<tr><td>*UPDATED*Apple</td><td>Pie</td></tr>
<tr><td>Orange</td><td>Crush</td></tr>
</table>
-
var $updatedContent = $('td:contains("*UPDATED*")');
$updatedContent.closest('td').css('border', '1px solid red').closest('tr').css('background','green');
$updatedContent.text($updatedContent.text().replace('*UPDATED*', ''));
Upvotes: 0
Reputation: 9644
Assuming the worst case, where you have nested tables and you cannot change current TD attributes, than print an empty span within it this way:
<table>
<tr>
<td>Content 1
<table>
<tr>
<td>Content 2<span data-class="very_important" /></td>
</tr>
</table>
</td>
</tr>
</table>
Than add class to (first or last) parent TR like this:
$(function() {
$('span[data-class]').each(function(n) {
var highlightClass = $(this).attr('data-class');
$(this).parents('tr:first').addClass( highlightClass );
$(this).remove(); /* Optional */
});
});
Now your TR has class and you can style it (and its children) the way you like. Result code:
<table>
<tr>
<td>Content 1
<table>
<tr class="very_important">
<td>Content 2</td>
</tr>
</table>
</td>
</tr>
</table>
Upvotes: 0
Reputation: 3848
here you can use parents() funciton.
if your element is $('#el') then following will give you nearest td and tr
$('#el').parents('td').first();
$('#el').parents('tr').first();
then you can apply operation like below
$('#el').parents('td').first().css("border", "1px solid red");
$('#el').parents('tr').first().css("border", "1px solid red");
Upvotes: 0