Reputation: 317
For some reason this code below is not alerting me the correct data-id when I click on one of the links.
This is what I have:
HTML
<a class="margin-0 size-9 serve" data-toggle="modal" data-target="#myModal2" data-id="3">Hello</a></p>
<a class="margin-0 size-9 serve" data-toggle="modal" data-target="#myModal2" data-id="4">Test</a></p>
Jquery
$(".serve").click(function(){ // Click to only happen on serve links
alert($(this).attr('data-id'));
});
Thanks in advance
Upvotes: 0
Views: 93
Reputation: 306
Works fine. Dommmmm's answer might be helpful if elements are generated dynamically after DOM is rendered.
$(".serve").click(function(){ // Click to only happen on serve links
alert($(this).attr('data-id'));
});
https://jsfiddle.net/n21ozzzr/
Upvotes: 1
Reputation: 8396
If your page was dynamically creating elements with the class name serve you would bind the event to a parent which already exists, often document.
$(document).on("click", ".serve", function (event) {
alert($(this).data('id'));
});
Upvotes: 3
Reputation: 767
For data
, use $(this).data("id")
:)
And for composite data (like data-foo-bar
), it's $(this).data("fooBar")
Upvotes: 0
Reputation: 908
I'm assuming you're generating elements dynamically to your webpage?
You have to initiate a click event handler for each new dynamic element you generate, and existing event handlers do not apply to newly generated DOM elements.
$(".serve")
is only applied to elements that are present at the moment the event handler is registered.
To get around this, you can instantiate event handlers for each new element that gets dynamically added:
eg.
function generateNewElementToPage() {
var newElement;
// your code here
$(parentContainer).append(newElement); // append your new element to page
$(newElement).click(function(){ // add event handler for newly created element
// do stuff here when event handler is triggered
});
}
Upvotes: 0