Hide table column whose checkbox is not checked on page load

hi all

this below code has 3 checkboxes.

these 3 checkboxes toggle hide/show table columns.

on page load i want to show only those columns of tables whose checkbox is checked.

if checkbox is not checked then i want to hide that column of table.

2nd checkbox is unchecked, so 2nd column of table should hide on page load by default.

how to hide 2nd column of table on page load by default or hide any column whose checkbox is not

checked ??

vineet

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>

<body>
<table border="1" cellpadding="5">
    <tr>
        <td class="Col1">Col 1</td>
        <td class="Col2">Col 2</td>
        <td class="Col3">Col 3</td>
    </tr>
    <tr>
        <td class="Col1">text 1</td>
        <td class="Col2">text 2</td>
        <td class="Col3">text 3</td>
    </tr>    
</table>

<br />

<table>
    <tr>
        <td><input name="Col1" type="checkbox" checked="checked" /></td>
        <td><input name="Col2" type="checkbox" style="margin-left:35px" /></td>
        <td><input name="Col3" type="checkbox" checked="checked" style="margin-left:35px" /></td>
    </tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('input:checkbox').change(function(){
   var col_name = $(this).attr("name");    
    if(this.checked){
        $("td[class='" + col_name + "']").show();        
    }else{
        $("td[class='" + col_name + "']").hide();
    }
});
</script>
</body>
</html>

vineet

I think this does what you want but of course when you hide a column the table shrinks and your checkboxes no longer line up with the right column.

$('input:checkbox').each(function(){
  toggleColumn(this);
});
$('input:checkbox').change(function(){
  toggleColumn(this);
});

function toggleColumn(el){
	var col_name = $(el).attr("name");    
    if(el.checked){
        $("td[class='" + col_name + "']").show();        
    }else{
        $("td[class='" + col_name + "']").hide();
    }

}

Thanks PaulOB

It is working perfect.

i know about the alignment of checkbox. i will rectify them.

thanks
vineet

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.