I have a table, where I display some data. Every table row has a ID. This ID is the value of every tr-tag. When I click a row of the table, I want to display the ID in the console.
Table:
$.getJSON(`http://localhost:5000/Flights/Flights/${fromAirport}/${toAirport}`)
.then(data => {
console.log(data);
$('#flights').find("tr:gt(0)").fadeOut().empty();
for (let item of data) {
console.log('entered loop');
$(`<tr value="${item.flightId}">`).appendTo('#flights')
.append($('<td>').html(item.date))
.append($('<td>').html(item.departureTime))
.append($('<td>').html(item.arrivalTime))
.append($('<td>').html(item.flightNr))
.append($('<td>').html(item.price))
.append($('<td>').html(item.airplane))
.append($('<td>').html(item.nrSeats))
.append($('<td>').html(item.nrVacant))
.append($('<td>').html(item.nrBooked))
.append($('<td>').html(item.flightId))
}
});
On Click Method:
$('#flights').on('click', function (e) {
const entry = $(e.target.val());
console.log(entry);
});
This on click event is not working, but I do not really know why. Maybe someone has a idea 🙂
2
Answers
There are a couple of errors here:
tr
.A syntax error:
.val()
is a jQuery function, you can’t use iton the
target
, you have to close the parens before:$(e.target).val()
.Even then
.val()
is used forinputs
, for this you have to access the attribute directly.All together, using event delegation, you can do the following:
Do you mean this?
When the user clicks on a tr, it receives the value