cooltoad
cooltoad

Reputation: 171

Attempting to hide a column of a html table using jQuery

function func(id) 
    {

        $(document).ready(function () 
        {
            $(".toggle").click(function () 
            {
                $("td:nth-child(" + id + ")>div").toggle();

            });
        });
        return false;
        }

Am attempting to hide the column corresponding to the button clicked. But this code gets some unexpected output like both the columns hiding when one button is clicked. where am i going wrong?

<table border="1">
<tr>
 <th><button class="toggle" id="1" onclick="return func(this.id);" >hide</button></th>
  <th><button class="toggle" id="2" onclick="return func(this.id);" >hide</button></th>
  </tr>
  <tr>
  <td> <div>row 1, cell 1</div></td>
  <td><div>row 1, cell 2</div></td>
  </tr>
  <tr>
  <td><div>row 2, cell 1</div></td>
  <td> <div>row 2, cell 2</div></td>
  </tr>
  </table>

Upvotes: 2

Views: 2927

Answers (2)

Edper
Edper

Reputation: 9322

You don't need onclick on your html to call the function.

In your jquery you could have:

$("#1,#2").click(function(){
$(this).find("td").hide();
});

Edit:

This one without resorting to giving id names to column:

$(document).ready(function(){
$("#1,#2").click(function(){
    var colid=$(this).prop("id");
    $("tr").children().each(function(){
        if (colid==1)
        {
           $(this).closest("td:nth-child(1),th:nth-child(1)").hide();                
        }
        else
        {
            $(this).closest("td:last-child,th:last-child").hide();
        }

    });
});

});

Here's the actual fiddle.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

An easier way to do this is to add a class to your columns td. I added class col1 and col2 to each of your td's.

Fiddle: http://jsfiddle.net/tbpMX/

Code:

$(".toggle").click(function() {
    $(this).parent().hide();
    $(".col" + $(this).attr("id")).hide();
});

Upvotes: 1

Related Questions