I want to change the <tr>
color when I click the <td>
inside of it and remove the color when I click on another <td>
in the same table (I have multiple tables) ? The problem is I already have a onclick function that I need.
here is my html:
<table class="table table-sm mb-0">
<thead>
<tr>
<th scope="col">Plant</th>
<th scope="col">Location</th>
<th scope="col" class="text-center">Total Pallet</th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
here is my JS:
$.each(data, function (key, value) {
html += "<tr>"
+ "<td>" + value["plant_name"] + "</td>"
+ "<td>" + value["loc_name"] + "</td>"
+ "<td class='pointer text-center' onclick='getModelData("" + value["werks"] + "", "" + value["lgort"] + "")'><u>" + value["total"] + "<u></td>"
+ "</tr>";
});
$("#rows").html(html);
I have tried adding another function inside the onclick but there is no result
function getOtherData() {
var row = $(this);
row.css('background-color', 'red');
}
2
Answers
To be able to set the parent
tr
of the clicked element to have a red background the event handler you bind must be able to get a reference to that element. UsingonX
attributes do not get this out of the box – you need to pass the element as an argument manually. This is part of the reason they are not good practice and should be avoided.Also note that there are several other things you can do to improve the quality of your code, such as using
map()
and a template literal to build your HTML which should be appended to the table, using CSS to style the UI instead of the<u>
element, using classes to dynamically update the UI instead of explicitly settingstyle
on the element itself and finally adding unobtrusive event handlers.Here’s a working example with all the above amendments made. Note the use of
data
attributes instead of passing arguments in theonclick
attribute.Simply bind another click event on your
td
and remove all background before adding new background to clicked item. See the following example.