Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a <td> clickable and get the value in javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading