Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/hide tables with jQuery

I have a series of tables similar to the following html code:

<table id="film"><tr>
       <th class="1">//HEAD CONTENT 1//</th>
       </tr>
       <tr>
       <td class="1">//BODY CONTENT 1//</td>
       </tr></table>
<table id="film"><tr>
       <th class="2">//HEAD CONTENT 2//</th>
       </tr>
       <tr>
       <td class="2">//BODY CONTENT 2//</td>
       </tr></table>

I want the tables to expand individually when the respective head (<th>) is clicked. Moreover the tables should start unexpanded. I use the following jQuery script:

$(document).ready(function(){
    $('#film td').hide();
});

$(document).ready(function(){
var n1 = 0;
      $('#film th.1').click(function(){
         if(n1 == 0){
         $('#film td.1').show();
         n1 = 1;
         }else{
        $('#film td.1').hide();
         n1 = 0;}
       });
var n2 = 0;
      $('#film th.2').click(function(){
         if(n2 == 0){
         $('#film td.2').show();
         n2 = 1;
         }else{
        $('#film td.2').hide();
         n2 = 0;}
       });
});

However when I execute only the top table is able to show/hide not the second one. Can anyone see where I'm going wrong?

like image 254
Andreas Jarbol Avatar asked Sep 14 '11 17:09

Andreas Jarbol


People also ask

How to hide table in jQuery?

In the click event of button, tr:odd selector is used with table class to hide the rows. You may simply use “tr:odd” as well, however, this will hide all tables odd rows in the web page.

How to hide table tr in jQuery?

Use . hide() method of jQuery to hide it as you just need to hide it.

How do I show and hide a table in HTML?

Approach 1: Select the header using a CSS selector and modify the style property such that the value of the display property is set to none. This will hide the selected table header element from the page. Example: html.


2 Answers

You are using the same id on multiple elements. When you search by id, jQuery will only return one item (the first with that id). So your code is only acting on the first table. Use a class on the tables instead of an id.

<table class="film">......</table>

$('.film').each(function(f) {
    //this function will execute for each element with the class "film"
    //refer to the current element during this function using "$(this)"
});
like image 165
yoozer8 Avatar answered Sep 28 '22 08:09

yoozer8


Using this jQuery you can show & hide

$("#hide").click(function(){
        $("p").hide();
    });
    $("#show").click(function(){
        $("p").show();
    });

html

<button id="hide">Hide</button>
<button id="show">Show</button>
like image 33
Madhuka Dilhan Avatar answered Sep 28 '22 08:09

Madhuka Dilhan