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.
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)
});