Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can't get data-id from <td> onclick

I have the following code creating a td

html += "<td data-id='test' class='journal' style='max-width:200px;'>"+record.source_account_code+"</td>";

and then the following code

    $(document).on('click', '#table-content td', e => {
   console.log("td onclick called")
   console.log($(this).attr('data-id'))
});

which executes correctly but instead of outputting "test" I get "undefined"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried doing it this way as well

$(this).data("id")

>Solution :

Use a regular function, not an arrow function:

$(document).on('click', '#table-content td', function() {
  console.log("td onclick called")
  console.log($(this).attr('data-id'))
});


document.querySelector('#table-content').innerHTML += "<td data-id='test' class='journal' style='max-width:200px;'>record</td>";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table-content"></table>

This is because jQuery will bind the event target to the function, which is why this will refer to the element. You can’t bind to an arrow function however. It’s an ES6 quirk.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading