How to go through all columns of a jquery table and hide if empty

Asked

Viewed 808 times

0

I have a table html with 15 lines and I need to go through all the columns and check if there is any value, if Column is equal to empty then hidden this column, I know that this example below hides the column position 5, but how to go through the columns ?.

$('#btnBuscar').on('click', function () {

    //Percorro todas as colunas
    //Se coluna vazia então oculto essa coluna

    $('.grid td:nth-child(5), th:nth-child(5)').hide();

});

1 answer

2


You need to scroll through the table using $.each, and add a bookmark to have control of the elements that will be deleted, for example...

$(document).ready(function(){
	$('.ocultar').on('click', function(){
  	var i = 1;
  	$('table.click tr td').each(function(el){
    
    	if($(this).text() == '') {
      
      	$('table.click td:nth-child('+i+'), th:nth-child('+i+')').hide(); 
        
        }
        
        i++;
      
    })
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="click">

<tr>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
</tr>
<tr>
  <td>teste1</td>
  <td></td>
  <td>teste3</td>
  <td>teste4</td>
  <td></td>
  <td>teste6</td>
  <td>teste7</td>
  <td></td>
  <td>teste9</td>
  <td>teste10</td>
  
</tr>

</table>
<button class="ocultar">
Ocultar
</button>

  • Hello @Felipe Duarte works, but the button btnBuscar makes a submit in view in order to load the data from the Client, however the function that hides the columns is executed before, that is to say me occult and in the sequence is made a refresh in the table, because I use the same button that makes Submit I need to hide the columns after the table has been fully loaded, there is a way around it ?

  • solved, put the code at the end of the script and worked!

  • another question related to this post occurred to me and if you can assist me I thank you (https://answall.com/questions/213481/traver-everyone-table-html-e-occur-caso-somecoluna-5-seja-v)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.