0

I dynamically generated a table from a database. I stored the data key as a data attribute. Now I want to get it out so I can use it but I keep getting undefined.

var row = "<tr class= 'trainInfo' data-key='" + dataKey + "'><td data- 
key='" + dataKey + "' >"
$('.table').append(row + (childSnapshot.val().train) +
"</td><td>" + (childSnapshot.val().destination) + "</td><td>" +
(childSnapshot.val().frequency) + "</td><td>" + (nextArrival) +
"</td><td>" + (minutesAway) + "</td></tr>");

$(document).on("click", "tr.trainInfo", function addRemove() {
    var changeTrain= $(this).attr("data");
    console.log(changeTrain)
});

I know there have been loads of questions on this but I am really new to coding and I still can't seem to make it work.

PaulaMacT
  • 77
  • 1
  • 8
  • Possible duplicate of [How to get the data-id attribute?](https://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute) – Heretic Monkey Mar 22 '18 at 21:41

1 Answers1

0

maybe

$(this).data("key");

it depend on jQuery version

or

$(this).attr("data-key");

in you case my code will be

$(document).on("click", ".trainInfo", function() {
//    var changeTrain= $(this).attr("data-key");
//    or 
      var changeTrain=$(this).data("key");
    console.log(changeTrain)
});
Jehad Ahmad Jaghoub
  • 1,225
  • 14
  • 22
  • I have tried both and I get back undefined. When I look in the elements section of the console you can see the data-key attribute is there – PaulaMacT Mar 22 '18 at 21:35