Get the value of a table

0

Good morning I want to get a value from this table when I click:

<table>
<th>2016</th>
<th>2017</th>
<th>2018</th>
<th>2019</th>
<th>2020</th>
</table>

With this function:

$("table").click(function(){
    alert($(this).find("th").eq(1).html());
    });

It does not work for me, I hope someone can tell me what I'm doing wrong.

    
asked by David Melo 10.04.2018 в 17:37
source

2 answers

1

The following code will alert you to the value of the element clicked:

$("table th").click(function(){
  alert($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <th>2016</th>
  <th>2017</th>
  <th>2018</th>
  <th>2019</th>
  <th>2020</th>
</table>

If you click on the table, and you want to return only the first value, your JavaScript function can be this way, using: first-child

$("table").click(function(){
  alert($("table th:first-child").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <th>2016</th>
  <th>2017</th>
  <th>2018</th>
  <th>2019</th>
  <th>2020</th>
</table>
    
answered by 10.04.2018 / 17:54
source
-1

You have to iterate through all the 'th' of your table, for each of them, you take the value:

var thCount = $('table th').length;
$("table").click(function(){
for(var i = 0; i< thCount; i++){
alert($(this).find("th").eq(i).html());
}});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<th>2016</th>
<th>2017</th>
<th>2018</th>
<th>2019</th>
<th>2020</th>
</table>
<script>
var thCount = $('table th').length;
$("table").click(function(){
for(var i = 0; i< thCount; i++){
alert($(this).find("th").eq(i).html());
}
    
    });
</script>
    
answered by 10.04.2018 в 17:55