How to pass the dynamic id of a Div to a javascript function?

1

I'm doing a dynamic table in html and need to display the subtable just when I click on tr from the main table, follow the example.

$(function () {
   $('#toggle3').click(function () {
       $('.toggle3').toggle('slow');
       return false;
   });
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><table><thead><tr><th>Nome</th><th>Dependentes</th><th>Quantidade</th></tr></thead><tboby><tr><td>Fulano</td><td><ahref="#" id="toggle3">convenio</a></td>
      <td>3</td>
    </tr>
    <tr>
      <td colspan="3"> 
        <div class="toggle3" style="display:none;">
<table width="200" border="6">
  <thead>
    <tr>
    <th>Nome</th>
    <th>Tipo</th>
    <th>Idade</th>
    </tr>
   </thead>
  <tr>
    <td>Maria</td>
    <td>Esposa</td>
    <td>47</td> 
    </tr>
  <tr>
    <td>Ana</td>
    <td>Filha</td>
    <td>12</td> 
    </tr>
  <tr>
    <td>Joaquim</td>
    <td>Filho</td>
    <td>06</td> 
  </tr>
  </table>
  </div>
       </td>
    </tr>
  </tbody>
  </table>

But in case I have multiple employees how do I pass the id value dynamically? Within while I put a $x++ variable that interacts with each new employee, and in the link I put the toogle name plus the value of the interaction

<a href="#" id="toggle<?php echo $x; ?>">link</a>

But I do not know how to retrieve this value in javascript

    
asked by anonymous 10.02.2017 / 02:38

2 answers

1

The following way you capture the click using $('td a').click() and the ID in var tmp = this.id; :

$(function () {
  $('td a').click(function () {
    var tmp = this.id;
    $('.'+tmp).toggle('slow');
    return false;
  });
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><table><thead><tr><th>Nome</th><th>Dependentes</th><th>Quantidade</th></tr></thead><tboby><tr><td>Fulano</td><td><ahref="#" id="toggle3">convenio</a></td>
      <td>3</td>
    </tr>
    <tr>
      <td colspan="3"> 
        <div class="toggle3" style="display:none;">
<table width="200" border="6">
  <thead>
    <tr>
    <th>Nome</th>
    <th>Tipo</th>
    <th>Idade</th>
    </tr>
   </thead>
  <tr>
    <td>Maria</td>
    <td>Esposa</td>
    <td>47</td> 
    </tr>
  <tr>
    <td>Ana</td>
    <td>Filha</td>
    <td>12</td> 
    </tr>
  <tr>
    <td>Joaquim</td>
    <td>Filho</td>
    <td>06</td> 
  </tr>
  </table>
  </div>
       </td>
    </tr>
  </tbody>
  </table>
    
10.02.2017 / 11:18
2

Good evening!

I suggest creating an attribute for the table row.

Example:

<table>
    <tbody>
        <tr data-id="2">
        </tr>
    </tbody>
</table>

In javascript try the following:

$('body').on ('click', 'table > tbody > tr', function (event) {
    event.preventDefault ();

    var linhaId = 0;
    if ($(this).attr('data-id')) {
        linhaId = $(this).attr('data-id');
    }

    ///
});
    
10.02.2017 / 02:56