Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide column/td of the table by using jquery

Tags:

html

jquery

css

How can we hide the column of the table by using jquery

< table >
  < tr >
   < td id="td_1" >name</ td >
   < td id="td_2" >title</ td >
   < td id="td_3" >desc</ td >
  </ tr >
  < tr >
   < td id="td_1" >Dave</ td >
   < td id="td_2" >WEB DEV</ td >
   < td id="td_3" >Blah Blah</ td >
  < /tr >
  < tr >
   < td id="td_1" >Nick< /td >
   < td id="td_2" >SEO< /td >
   < td id="td_3" >Blah Blah and blah< /td >
  < /tr >
< /table >

So suppose if someone want to hide first column i.e. td_1 from all rows, then what will be the code ?

Thanks in Advance Dave

like image 233
dave Avatar asked Jul 21 '10 05:07

dave


2 Answers

$(document).ready(function() {
    $("#td_1").hide();
});

But ideally, you want to use a class instead of an ID.

so

<table>
  <tr>
   <td class="td_1">name</td>
   <td class="td_2">title</td>
   <td class="td_3">desc</td>
  </tr>
  <tr>
   <td class="td_1">Dave</td>
   <td class="td_2">WEB DEV</td>
   <td class="td_3">Blah Blah</td>
  </tr>
  <tr>
   <td class="td_1">Nick</td>
   <td class="td_2">SEO</td>
   <td class="td_3">Blah Blah and blah</td>
  </tr>
</table>

And then you would use similar code:

$(document).ready(function() {
    $(".td_1").hide()
});

So the only thing that changed is the hash(#) to a dot(.). Hash is for ID's, Dot is for classes.

Yet another way would be to use the nthChild selector.

$(document).ready(function() {
    $('tr td:nth-child(1)').hide();
});

Where 1 is the column number to be hidden.

HTH

like image 175
Marko Avatar answered Oct 16 '22 06:10

Marko


Some case, user use th for table header, you can use this script for hide column with th.

$('#test').click(function() {
    $('th:nth-child(2), tr td:nth-child(2)').hide();
})

$('#test').click(function() {
    $('th:nth-child(2), tr td:nth-child(2)').hide();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border=1>
  <tr>
   <th id="td_1">name</th>
   <th id="td_2">title</th>
   <th id="td_3">desc</th>
  </tr>
  <tr>
   <td id="td_1">Dave</td>
   <td id="td_2">WEB DEV</td>
   <td id="td_3">Blah Blah</td>
  </tr>
  <tr>
   <td id="td_1">Nick</td>
   <td id="td_2">SEO</td>
   <td id="td_3">Blah Blah and blah</td>
  </tr>
</table>

<button id='test'>Hide title</button>
like image 44
Hien Nguyen Avatar answered Oct 16 '22 05:10

Hien Nguyen