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?
To do that, you can use the ping attribute of the anchor tag. A ping attribute accepts one or more URLs as values.
In the text editor, click SOURCE. Navigate to where you want to insert an anchor. In the HTML code, insert the anchor using the format id=“anchor_name” within the <p> tag. Note: IDs on a page must be unique, and can't be re-used for other anchors.
HTML <a> data-* Attribute. A data-* attribute on an <a> tag attaches additional data to the anchor element. To create a custom attribute, replace * with a lowercase string, such as data-id , data-status , or data-location .
Do not use an anchor with an onclick event without an href element event.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With