Search code examples
jqueryhidecol

Simple Jquery code to hide column


This is the first time ever, that I have posted on StackOverflow. The reason being, I have always found a solution each time I searched stackoverflow for it.

However this time I am still struggling to find a simple solution like the code I am using here. (Found on W3Schools) I have already looked at some very advanced and complicated Hide/Reveal tables functionalities, but I am after something simply like below. The current code very easily hides a whole when clicked on. I wanted to know, if the same can be applied for a column.

I tried using col, colgroup but it does not work. Can someone please suggest? Also tried applying TH, but that doesn't work too.

PS: I understand HTML & CSS very well, and some very basic PHP, I have used Jquery sparingly, but cannot completely read and understand javascript well enough to make my own modifications or write my own code yet.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("tr").click(function(){
    $(this).hide();
  });
});
</script>
</head>
<body>
<table width="800" border="0" cellspacing="1" cellpadding="1">
  <tr>
    <td bgcolor="#6600FF">9</td>
    <td bgcolor="#6600FF">10</td>
    <td bgcolor="#6600FF">11</td>
    <td bgcolor="#6600FF">12</td>
  </tr>
  <tr>
    <td bgcolor="#CCCC66">13</td>
    <td bgcolor="#CCCC66">14</td>
    <td bgcolor="#CCCC66">15</td>
    <td bgcolor="#CCCC66">16</td>
  </tr>
  <tr>
    <td bgcolor="#FF9966">17</td>
    <td bgcolor="#FF9966">18</td>
    <td bgcolor="#FF9966">19</td>
    <td bgcolor="#FF9966">20</td>
  </tr>
  <tr>
    <td bgcolor="#993399">21</td>
    <td bgcolor="#993399">22</td>
    <td bgcolor="#993399">23</td>
    <td bgcolor="#993399">24</td>
  </tr>
</table>

<blockquote>&nbsp;</blockquote>
</body>
</html>

Solution

  • Try

    $(document).ready(function(){
        $("td").click(function(){
            var idx = $(this).index();
            $('table tr').find('td:eq(' + idx + ')').hide()
        });
    });
    

    Demo: Fiddle