Question

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?

Was it helpful?

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

OTHER TIPS

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.

One more simple way is:

  1. Use id attribute in anchor tag to write your data.

<a id="your-data" onclick="callfunction(this.id)">Fixed</a>

  1. Create a function in js file like callfucntion(id).

function callfucntion(id) { var data = id; // if more than one data, you can se split() }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top