user2166059
user2166059

Reputation: 35

How do I collapse these tables individually?

I have multiple tables each nested in its own div tag. When I try to close just one table they all close. HTML:

<div>
<p>Table Title</p>
<table>
table content
</table>
</div>

<div>
<p>Table Two Title</p>
<table>
table content
</table>
</div>

Jquery:

<script>
    $("p").click(function(){
    $("table").slideToggle("fast");
    });
</script>

The HTML looks legit, new to Jquery so the problem might be in that code.

Upvotes: 0

Views: 28

Answers (3)

Wes Duff
Wes Duff

Reputation: 373

<script>
  $("p").click(function(){
    var self = $(this); //for speed and OBJECT this placement
    //get the table
    var table_to_toggle = self.next(); //by your HTML the next DOM element should be the table.
    table_to_toggle.slideToggle("fast");
});
</script>

So you need to access the table related to the "p" tag you chose. Then close that table. I used .next() to grab the next DOM node in the DOM tree structure. Then you can manipulate the DOM element you want instead of ALL of the table elements.

Note **

$("table")

selects ALL the tables in the DOM.

console.log($("table").size());

This will tell you how many tables were selected

Go into your console under Developer Tools and put this inside your console.

$("table")

It will print out all of the tables. Then you can hover over each one and see what was selected. It is a good way to test your jQuery before you commit the code.

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Use this to get the clicked p tag and then select the table using .next function.

$("p").click(function() {
  $(this).next("table").slideToggle("fast");
});
table { display:  block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>
  <p>Table Title</p>
    <table>
      <tr>
        <td>table content</td>
      </tr>
    </table>
</div>

<div>
  <p>Table Two Title</p>
    <table>
      <tr>
        <td>table content</td>
      </tr>
    </table>
</div>

Upvotes: 1

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2596

Your selector is not right.

$("table") //select all the table

Try this :

$("p").click(function(){
    $(this).next("table").slideToggle("fast");
});

Upvotes: 0

Related Questions