3

I have a table with one link as follows

 <td>
      <a href="#" class="topiclink">@item.Topic</a>
   </td>

I want to select data of @item.topic. I tried using

  $('.topiclink').click(function (e) {
  var val = $(this).closest('a');
        alert(val)
    });

and many others but nothing seems working in this case.Thank for the help.

S.p
  • 1,059
  • 3
  • 15
  • 27

4 Answers4

4

What you've clicked is already an anchor, so:

$('.topiclink').on('click', function (e) {
    var val = $(this).text();
    alert(val);
}

I'm also using .text() here, because .val() should only be used on HTML input elements.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2
var val = $(this).text(); 

Is enough to get you that

Raab
  • 34,778
  • 4
  • 50
  • 65
2

If you're trying to get the value '@item.Topic' on click of the anchor or any anchor, that is, you may use below code:

$('a').click( function () {
   console.log($(this).text());
});
KevinIsNowOnline
  • 773
  • 4
  • 10
0

A lot of errors in your code ! Your element is already a '.topiclink' class, so why do you want the closest element ? Just use $(this) to access your element. val() not return the html of the element, you should use $(this).html();

 $('.topiclink').click(function (e) {
    alert($(this).html()); 
 }
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
  • 1
    Don't use `InnerHTML` or `HTML()` it gives you the HTML elements inside the Anchor tag not the Text... See here : http://jsfiddle.net/pacFf/3/ – Pandian Apr 23 '13 at 12:30