Without so much code can be fixed by putting 1 button, instead of 2.
Unless it's strictly necessary, I think it's better if you only have one button, that you make toggle
that commutes the visibility of the column.
To do this, we select the header with $(".pais")
and hide it or show it with .toggle()
.
To hide / show the rows, we can make a small filter like this:
$('td:nth-child(3)')
which means: Take the td
that are your father's third child. The parent is the row tr
and the third child is the td
in the Country column.
and to them you apply the toggle()
as well.
With this you save putting the class
to each element you want to hide.
$("#boton").on("click", function(){
$(".pais").toggle();
$('td:nth-child(3)').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th class="pais">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
</table>
<button id="boton">Ocultar/Mostrar columna pais</button>