Rob L
Rob L

Reputation: 2372

Accessing data("") from dynamically created list items

jQuery 2.2.3

I have a dynamic list of elements, that get created/removed on the fly:

<ul id="tracks">
    <button class="createRace" data-trackcode="410243">Create Race</button>
    <button class="createRace" data-trackcode="123540">Create Race</button>
    ...
</ul>

I am using the following technique to react to button clicks.

$("#tracks").on("click", ".createRace", createRaceClick);

My createRaceClick() function is being called, but the "this" object is referencing #tracks, not the button that was pressed.

How can I determine which button was pressed? Or more specifically, how can I get the data("trackcode") associated with the actual button that was pressed.

Thanks

Upvotes: 3

Views: 28

Answers (1)

The Process
The Process

Reputation: 5953

Well that is strange, since in that context of event delegation, this should refer to the button that was clicked. However you can use target property of the event object to get the .createRace that raised the click event:

$("#tracks").on("click", ".createRace", createRaceClick);

function createRaceClick(e){

  var data=$(e.target).data('trackcode'); //  $(this).data('trackcode') should work
}

Upvotes: 1

Related Questions