rawatdeepesh rawatdeepesh - 2 months ago 11
jQuery Question

hide all td in a table excluding the clicked one

I have a fieldset in which I have a table with multiple tr and td . I have to hide all the td upon click event except the td that is clicked inside the fieldset.
I tried traversing to the parent tr of the tds that have to be clicked and then set the css to "display:none" . But it seems to hide all the td instead.

Here is my fiddle. Could this be achieved using the same the same traversals .

$('#fieldset_QCNew table tbody tr td:nth-child('+index+')').css("display","none");


https://jsfiddle.net/rawatdeepesh/dzg68ajk/1/

Answer

Here is what you need:

$(function() {
    $('td').on('click', function() {
        $(this).closest('table').find('td').not(this).toggle();
    });
});

NOTE: If you'd like the cells to maintain their positions then using .css("visibility", "hidden") rather than .hide() or toggle -- which use .css("display", "none") -- would achieve that.

$(function() {
    $('td').on('click', function() {
        $(this).closest('table').find('td').not(this).toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Col A</th>
      <th>Col B</th>
      <th>Col C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1,1</td>
      <td>1,2</td>
      <td>1,3</td>
    </tr>
    <tr>
      <td>2,1</td>
      <td>2,2</td>
      <td>2,3</td>
    </tr>
    <tr>
      <td>3,1</td>
      <td>3,2</td>
      <td>3,3</td>
    </tr>
  </tbody>
</table>