Search code examples
javascriptjqueryhtmlanchorhref

How to add data to the anchor tag in HTML and access it using jQuery?


Following is my HTML code of an anchor tag:

<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21627&que_issue_status=0" title="Fixed" href="#fixedPopContent" class="fixed">Fixed</a>

Now I want to add a question id to the above anchor tag and access it back in jQuery when user clicks on this hyperlink. For it I tried below code but it didn't work out for me.

<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21627&que_issue_status=0" title="Fixed" href="#fixedPopContent" class="fixed" data="21627">Fixed</a>

The jQuery code for it is as follows:

$(document).ready(function()  {
  $(".fixed").click(function(e) {
    var t2 = $(this).data();
    alert(t2);
  });
});

It's giving me the message [object Object] in alert box. Can anyone please help me in setting the value to a anchor tag and accessing it in jQuery?


Solution

  • try something like this

    html

     <a  href="#fixedPopContent" class="fixed" data-q_id="21627"></a>
    

    javascript

    $(document).ready(function()  {
      $(".fixed").click(function(e) {
        var t2 = $(this).data('q_id');
        alert(t2);
      });
    }); 
    

    you can add attribute data-sample_name on your html element. In jquery use

    $('your_element_id').data('sample_name');// to get value
    $('your_element_id').data('sample_name','new value');// to set  value