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

17,862

Solution 1

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

Solution 2

I assume you are trying to do something like this:

$(document).ready(function()  {
  // you can change the selector, `"key"` and its value below
  $("a.fixed").data("key", 21627); // on document ready, store the necessary data
  //                        ^-- Insert a dynamic value here if required

  $(".fixed").click(function(e) {    
    alert($(this).data("key"));  // 21627
  });

});

.data() stores a key-value pair. So here, I made a key called 'key' and stored with it a value of 21627 and on click, alerted the value corresponding to the key 'key'.

You got a [object Object] because of the same reason that .data() stores data in an object and that by passing it zero arguments, you were essentially storing the object associated with .fixed into t2.

Share:
17,862
PHPLover
Author by

PHPLover

Updated on June 09, 2022

Comments

  • PHPLover
    PHPLover almost 2 years

    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?

  • PHPLover
    PHPLover about 10 years
    Actually the value I'm assigning to data attribute is dynamic. For the purpose of understanding I'd given (21627) a hardcoded value. I want a solution which would is generalized.
  • Gaurang Tandon
    Gaurang Tandon about 10 years
    No problem then also, you can pass to the call of $("a.fixed").data("key", 21627); a dynamic value in place of 21627 .
  • 151291
    151291 about 8 years
    will it support all version of browsers?