user1322114
user1322114

Reputation: 317

How do you fetch a dynamic id from a list?

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

Answers (4)

Piyush Khanna
Piyush Khanna

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

Monzurul Shimul
Monzurul Shimul

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

Gregoire
Gregoire

Reputation: 767

For data, use $(this).data("id") :) And for composite data (like data-foo-bar), it's $(this).data("fooBar")

Upvotes: 0

dommmm
dommmm

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

Related Questions