user7689729
user7689729

Reputation:

JQuery - Hide Table Columns

I am currently learning about JQuery. I've saved the JQuery file in my wwwroot folder. The script and HTML is as follows:

<head>
<script src="jquery-3.2.0.js">
</head>
<script>
$("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).hide();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});
</script>
<p><input type="checkbox" name="first_name" checked="checked"> First Name 
  <input type="checkbox" name="last_name"> Last Name 
  <input type="checkbox" name="email" checked="checked"> Email</p>

<table id="report">
<thead>
<tr>
 <th class="first_name">First Name</th>
 <th class="last_name">Last Name</th>
 <th class="email">Email</th>
</tr>
</thead>
<tbody>
<tr>
 <td class="first_name">Larry</td>
 <td class="last_name">Hughes</td>
 <td class="email">[email protected]</td>
</tr>
<tr>
 <td class="first_name">Mike</td>
 <td class="last_name">Tyson</td>
 <td class="email">[email protected]</td>
</tr>
</tbody>

I'm trying to add and remove columns via the checkbox, but its simply not working. I cannot understand why it wouldn't work? Does anybody have any ideas?

Upvotes: 0

Views: 155

Answers (2)

AE1
AE1

Reputation: 77

wrap your code in document.ready function

  $(document).ready(function () {     
       $("input:checkbox:not(:checked)").each(function() {
            var column = "table ." + $(this).attr("name");
            $(column).hide();
        });

        $("input:checkbox").click(function(){
            var column = "table ." + $(this).attr("name");
            $(column).toggle();
        });
   });

Upvotes: 1

Nirnae
Nirnae

Reputation: 1345

I think you're trying to do the following :

$(document).on('change', 'input:checkbox', function() {
    if($(this).is(':checked')){
        var column = "table ." + $(this).attr("name");
        $(column).toggle();
    }else{
      var column = "table ." + $(this).attr("name");
        $(column).hide();   
    }
});

Do detect a modification on a checkbox. Ref : How to detect a checkbox click in jQuery

Upvotes: 1

Related Questions