sTg
sTg

Reputation: 4434

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?

Upvotes: 2

Views: 63

Answers (3)

Vishal Gupta
Vishal Gupta

Reputation: 132

There is no need of binding jquery click you can even pass this in your function as a param and get the value from this parameter.

Upvotes: 0

Samudrala Ramu
Samudrala Ramu

Reputation: 2106

You could Retrieve That Particular Clicked Item On Anchor With .text() Then Its Works. Try It Once

$(document).on('click', '#tableData td a', function() {
  var value = $(this).text();
  alert(value);
});
<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>
  <tr>
    <td><a href="#">Nokia</a></td>
    <td>23-May-2016</td>
  </tr>
  <tr>
    <td><a href="#">SamSung</a></td>
    <td>23-May-2016</td>
  </tr>
</table>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337743

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.

Upvotes: 5

Related Questions