skip to Main Content

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


  1. There are a couple of errors here:

    • The target of the click is the table itself, you have to select the
      tr.
    • A syntax error: .val() is a jQuery function, you can’t use it
      on the target, you have to close the parens before: $(e.target).val().

    • Even then .val() is used for inputs, for this you have to access the attribute directly.

    All together, using event delegation, you can do the following:

    $('#flights').on('click', 'tr', function() {
      console.log($(this).attr('value'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="flights">
      <tr value="1">
        <td>Item1</td>
      </tr>
      <tr value="2">
        <td>Item1</td>
      </tr>
    </table>
    Login or Signup to reply.
  2. Do you mean this?

    When the user clicks on a tr, it receives the value

    $('tr').on('click',function(){
     value = $(this).attr('value');
     console.log(value);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search