laker001
laker001

Reputation: 417

Show and hide table column using jQuery

I came across this fiddle from a SO answer, that hides a table column once a button is clicked. What i want is the absolute opposite. I want it to be hidden by default, and then show and hide (toggle) when i click a button.

How can i achieve this?

Here's the fiddle:

FIDDLE

HTML:

<table id="foo">
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>
<button onclick='document.getElementById("foo").classList.toggle("hide2")'>Click me</button>

CSS:

#foo td {
padding: 1em;
border: 1px solid black;
}

#foo.hide2 tr > *:nth-child(2) {
    display: none;
}

Upvotes: 1

Views: 1442

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Set the hide2 class initially to the element or execute the toggle statement once.

#foo td {
  padding: 1em;
  border: 1px solid black;
}
#foo.hide2 tr > td:nth-child(2) {
  display: none;
}
<table id="foo" class="hide2">
  <!------------^^^^^^^^^^^-->
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
</table>
<button onclick='document.getElementById("foo").classList.toggle("hide2")'>Click me</button>

Upvotes: 2

grec0o
grec0o

Reputation: 100

I know how to do it with JQuery adding this line.

$('td:nth-child(2)').hide();

http://jsfiddle.net/bnDVS/609/

And with CSS add it:

#foo td:nth-child(2) { display: none;}

And change it:

#foo.hide2 tr > td:nth-child(2) {
    display: none;
}

To:

#foo.hide2 tr > td:nth-child(2) {
    display: table-cell;
}

http://jsfiddle.net/bnDVS/610/

Upvotes: 1

Related Questions