Home » Jquery » jquery – add HyperLink to <td> in table with javascript

jquery – add HyperLink to <td> in table with javascript

Posted by: admin February 22, 2020 Leave a comment

Questions:

How can I add an hyperlink to a <td> in a dynamic table?

I need the 1st <td> to be an hyperlink to a url + cell value.

Table dynamic creation :

for (var i = 0; i < riskData.length; i++) {
  $("#grdDemo3").append("<tr><td>" + riskData[i].r_id +
    "</td><td>" + riskData[i].r_team + "</td></tr>");
}
How to&Answer:

Try this

for (var i = 0; i < riskData.length; i++) {
   $("#grdDemo3").append("<tr><td><a href='https://a.com/"+riskData[i].r_id +"'>" +riskData[i].r_id + "</a></td><td>" + riskData[i].r_team + "</td></tr>");

 }

OR

for (var i = 0; i < riskData.length; i++) {
   $("#grdDemo3").append("<tr><td onclick='window.location.href=\"htts://a.com/"+riskData[i].r_id +"\"'>" +riskData[i].r_id + "</td><td>" + riskData[i].r_team + "</td></tr>");

 }

Answer:

You can always add an anchor tag to td element and make it look like a whole table cell.

table {
  border-collapse: collapse;
}

td {
  border: 1px solid #CCCCCC;
  padding: 12px;
}

table tr td a {
  display: block;
  height: 100%;
  width: 100%;
  background: #F2F2F2;
  text-decoration: none;
}
<table>
  <tr>
    <td>
      <a href="https://www.google.com/"><span>Some Text</span></a>
    </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      hello here </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      <a href="https://www.google.com/"><span>Some Text</span></a>
    </td>
    <td>some content
    </td>
  </tr>
  <tr>
    <td>
      <a href="https://www.google.com/"><span>Some Text</span></a>
    </td>
    <td>some content
    </td>
  </tr>
</table>