Jquery taking the father of i

0

Well folks, I need to get the TR ID of the one clicked. My HTML is as follows:

<table id="datatable">
    <thead>
      <tr>
        <th>Nome</th>
        <th>Data de Nascimento</th>
        <th>Telefone</th>
        <th>Email</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      @foreach($clients as $client)
          <tr class="editLink" id="{{ $client->id }}">
            <td>{{ $client->name }}</td>
            <td>{{ $client->birthdate }}</td>
            <td>{{ $client->phone }}</td>
            <td>{{ $client->email }}</td>
            <td class="delete delete_client"><i  class="material-icons red-text delete-tupla">delete_forever</i></td>
          </tr>
      @endforeach
    </tbody>
  </table>

I'm using Laravel's Blade to iterate the object coming from the Controller, my question is this, if the user clicks on this in a <i> , how do I get the id that's in the tr it, I'm trying to do so:

$(this).closest('tr').html()

JS looks like this:

$(".delete_client").click(function(e){

  console.log($(this).closest('tr').html());

});

The problem is that it always takes the first iteration, if I have 10 lines, it always takes the first one, and I need to get the one from the one that was clicked.

Any tips?

Thanks, hugs

    
asked by anonymous 04.11.2017 / 16:24

2 answers

2

@Dvd's response was correct,

$(this).closest('tr').attr("id")

I was using .html (), so it was showing me all content within the TR and not the .attr ("id") to get the ID of the tr.

Thank you for responding.

    
04.11.2017 / 16:47
0

Once you are putting this in PHP you have 2 possibilities:

Passing ID with PHP with onclick="delete("{{ $client->id }}")" :

<tbody>
  @foreach($clients as $client)
      <tr class="editLink" id="{{ $client->id }}">
        <td>{{ $client->name }}</td>
        <td>{{ $client->birthdate }}</td>
        <td>{{ $client->phone }}</td>
        <td>{{ $client->email }}</td>
        <td class="delete delete_client" onclick="deleteRow("{{ $client->id }}")"><i  class="material-icons red-text delete-tupla">delete_forever</i></td>
      </tr>
  @endforeach
</tbody>

So you just need to have a function of name deleteRow that receives the ID.

Using JavaScript (or jQuery):

Here's more as less as you mentioned:

$(".delete_client").click(function(e){
  var id = this.closest('tr').id;
  // ou com jQuery
  // var id = $(this).closest('tr').attr("id");
}); 
    
04.11.2017 / 17:51