Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing data("") from dynamically created list items

Tags:

jquery

dynamic

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

like image 973
Rob L Avatar asked Jan 31 '26 11:01

Rob L


1 Answers

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
}
like image 88
The Process Avatar answered Feb 03 '26 06:02

The Process