I want to show/hide a column of a table using javascript/jquery .
Pressing a button shows or hides the entire column. The name of the column is the TH identified by an id I have achieved it by adding a class to each TD but I don't like this solution, I would like to achieve it without adding so much class attribute.
$(document).ready(function(){
$("#ocultar").click(function(){
$(".pais").hide();
});
$("#mostrar").click(function(){
$('.pais').show();
});
});
<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 class="pais">Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td class="pais">Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td class="pais">Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td class="pais">UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td class="pais">Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td class="pais">Italy</td>
</tr>
</table>
<button id="ocultar">Hide</button>
<button id="mostrar">Show</button>
Without so much code, it can be fixed by putting 1 button, instead of 2.
Unless strictly necessary, I think it's best if you only have one button, which
toggle
toggles the column's visibility.To do this, we select the header with
$(".pais")
and hide or show it with.toggle()
.To hide/show the rows, we can do a little filter like this:
which means: Take those
td
who are the third son of his father. The parent is the rowtr
and the third child is thetd
in the Country column.and to them you apply the
toggle()
too.With this you save yourself from putting the
class
to each element you want to hide.To hide with
JavaScript
, without Jquery, it occurs to me that since you already have a class that identifies them, you can use these to add a classhidden
, for example.If you also take into account the modification of
HTML
, you could remove the classes from eachtd
and just add aid
to the table as well as remove a button and have1
it just work as atoggle
, but all just with justJavaScript
You can also do the following from CSS:
Or have a hide class in CSS and via javascript, add the class:
Excuse me, I wanted to consult the following regarding something similar. If I have this code quoted from above:
How do I do it if I have another table next to it and hide only the columns of one table and not the 2... Thanks.