I’m trying to make a <td> clickable and get the value to javascript. I’ve got multiple <td> generated by my Django backend, one example:
<td class="hostname"><a href="javascript:void(0)"
onclick="clientInfo();">Client001</a></td>
When I click it triggers the JavaScript
function clientInfo() {
var $row = $(this).closest("tr");
var $hostname = $row.find("hostname").text();
alert($hostname);
}
but the $hostname stays empty.
The JS works with a button in a <td> the only thing that differs is the JS call with onClick().
>Solution :
I don’t know how the original looks like when you say it works.
But this in that function refers to the Window object. You can see about doing console.log(this). To fix that, you can try using the event object instead:
<table>
<tr>
<td class="hostname"><a href="javascript:void(0)"
onclick="clientInfo(event)">Client001</a></td>
</tr>
</table>
function clientInfo(e) {
var $row = $(e.target).closest("tr");
var $hostname = $row.find(".hostname").text();
console.log($hostname);
}