I am new to JavaScript and was trying to figure our how to access data attribute values of dynamically generated buttons. I was passing my ID coming from the Database to "data-id" attribute. Below is the dynamically generated code for my buttons
<button class='btn btn-sm btn-primary aButton' data-id='1234'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12345'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12346'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12347'></button>
Now i wanted to access these buttons onclick using jquery to perform some actions. Below is my code for that
$(document).on('click', '.aButton', () => {
let id = $(this).attr('data-id');
console.log(id);
})
The above console gives me "undefined" with the thick arrow function. When I tried to do the same with function () {}, it gave me the dynamic ID stored in the data attribute of the button.
What is happening with this? Is there a better approach to get a dynamic ID of button on click. Thank you all in advance. Have a nice day :)