Shirish Shirish - 2 months ago 6
jQuery Question

Get the value of a clicked link through Jquery?

I am trying to fetch the value of a clicked link but i am getting undefined.
Please find the code that i have been trying:

<table id="tableData" style="width: 100%;">
<tr>
<tr>
<td><a onClick="changeValue();">Apple</a> </td>
<td>23-May-2016</td>
</tr>
</table>


$(document).on('click', '#tableData td a', function () {
alert($(this).parent().attr('value'));
});


Now when i click on the
Apple
link I should get the value
Apple
but what I get is
undefined
. Can anyone please tell me where I am going wrong?

Answer

You need to retrieve the text() of the a, not the value attribute of the parent. Try this:

$(document).on('click', '#tableData td a', function(e) {
  e.preventDefault();
  console.log($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableData" style="width: 100%;">
  <tr>
    <td><a href="#">Apple</a></td>
    <td>23-May-2016</td>
  </tr>
</table>

Note that I also fixed some issues in your HTML, namely the redundant tr and onclick attribute, and added a href to make it valid.

Comments