I need to recover the title of the selected field in jquery! [closed]

-4

For example, when you click on 'Silva', display the title "Last name"

<pre>
<table>
  <tr>
    <th class='title'>Nome</th>
    <th class='title'>Sobrenome</th>
    <th class='title'>Idade</th>
  </tr>
  <tr>
    <td class='campo'>Carlos</td>
    <td class='campo'>Borges</td>
    <td class='campo'>50</td>
  </tr> <tr>
    <td class='campo'>Joao</td>
    <td class='campo'>Silva</td>
    <td class='campo'>22</td>
  </tr>
</table>
</pre>
    
asked by anonymous 08.12.2017 / 13:48

1 answer

0

Following is an example using JQuery.

$(document).ready(function() {
  $('td').click(function() {
    var titulo = $(this).closest('table').find('th').eq($(this).index()).text();
    alert(titulo);
  });
});
pre {
  font-size: 1.5em;
}

table {
  border-spacing: 10px;
  border-collapse: separate;
  min-width: 50px;
}

th {
  text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
<table>
  <tr>
    <th class='title'>Nome</th>
    <th class='title'>Sobrenome</th>
    <th class='title'>Idade</th>
  </tr>
  <tr>
    <td class='campo'>Carlos</td>
    <td class='campo'>Borges</td>
    <td class='campo'>50</td>
  </tr> <tr>
    <td class='campo'>Joao</td>
    <td class='campo'>Silva</td>
    <td class='campo'>22</td>
  </tr>
</table>
</pre>
    
08.12.2017 / 16:15