Revealing or Concealing a column with a Checkbox Toggle

Showing and Hiding Columns with Checkbox Selection

DISCLAIMER: I have exhausted all available solutions before posting this question, as none of them have worked for me so far. I joined specifically because the existing solutions did not meet my needs.

The purpose of my code is to dynamically generate a table and allow users to edit its contents. Each time a new column is created, a corresponding checkbox is added that, when unchecked, hides the associated column.

This is the code I am using:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.4.4.min.js"></script>
 <script type="text/javascript"             src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type='text/javascript'>
function addrow()
{    
 first_row = $('#Row1');
 first_row.clone().appendTo('random');
}
function addcol()
{
 var myform = $('#myform'),
 iter = 1;
 myform.find('tr').each(function(){
           var trow = $(this);
             if(trow.index() === 0){
                 trow.append('<th contenteditable="true" class="COLUMN_'+iter+'"><b>COLUMN # '+iter+'</b></td>');
                  var labelname = "Show COLUMN #" +iter;
            var create = $('<input type="checkbox" name="COLUMN_'+iter+'"     checked="checked"><label>'+labelname+'</label><br>');
           $(".noprint").append(create);
             }else{
                 trow.append('<td class="COLUMN_'+iter+'" contenteditable="true"></td>');
             }
         });
         iter += 1;       
}
$(window).load(function(){
$("input:checkbox").click(function(){
    var column = "."+$(this).attr("name");
    $(column).toggle();
});
});
</script>  
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
}
td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}
tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>
<input type="button" value="Add new row"     onclick="addrow()"/>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<input type="button" value="Add new column"     onclick="addcol()"/>
<br>
<br>
 <span class="noprint"> </span>
<form id="myform">
<table id="random" width="70%">
  <tr>
    <th>Name 1</th>
    <th>Name 2</th>
  </tr>
  <tr id="Row1">
    <td contenteditable="true">Entry 1</td>
    <td contenteditable="true">Entry 2</td>
  </tr>
  <tr>
    <td contenteditable="true">Entry 3</td>
    <td contenteditable="true">Entry 4</td>
  </tr>
</table>
</form>
</body>
</html>

I'm encountering difficulties in hiding columns based on the status of the checkboxes. Can anyone point out what mistakes I might be making?

Answer №1

Give this a shot...

$(“#myform”).on(“click”,”input[type=‘checkbox’]”,function(){
    var col = "."+$(this).attr("name");
    $(col).toggle();
});

If your checkbox elements are dynamically added, make sure to listen for the click event on the parent element and then bind to the child.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a duplicate <li> element and animate it using jQuery

Here are the list items: <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</l ...

Why does the checked pseudo class seem to be unresponsive?

I have been attempting to customize the appearance of radio buttons, but I am encountering issues with the checked pseudo-class. Interestingly, the hover effect is working perfectly. Although this is just a small section of a larger form, I am focusing o ...

enhancing feature to enable automatic selection of chosen option

I am facing an issue with a dropdown that utilizes ng-options in Angular. There is a default option selected with an empty value, indicated by the "selected" attribute and matching the model's value. Whenever I add a new element to the ng-options lis ...

Personalized Bootstrap 4.1 Toggle Animation

I have been attempting to implement a customized menu toggle on Bootstrap 4.0's Navbar menu, using the code provided by Codeply HERE. My goal is to apply the X toggle style to my website's bootstrap navbar. Below is the current setup I have imple ...

What methods can be used for child components to communicate in React and React-Native?

Is there a way for child components in React to directly call functions from one another, such as accessing test1() from test2() or vice versa? I already have access to both functions from the parent components through ref_to_test1 and ref_to_test2. But ...

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...

Switching the checkbox value upon clicking a div element

One challenge I am facing is with a checkbox that saves its value and title in the local storage when clicked. This checkbox is located within a div, and I want the checkbox value to change whenever any part of the div is clicked. Despite my efforts, I hav ...

What could be the reason behind the occurrence of an invalid hook error when utilizing an imported function

I'm currently working on creating a navigation bar for a dashboard page, but I've run into an issue. Everything works fine until I try to integrate the navbar by importing and executing the function. I can pinpoint that the problem occurs when in ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...

Difficulty being faced in recognizing anchor tags through CSS selector methods by Mechanize

(Just wanted to check here since I didn't get much response on RailsForum lately.) Has anyone encountered issues with Mechanize not picking up anchor tags using CSS selectors? Here's a snippet of the HTML code: <td class='calendarCell& ...

Check out this unexpected margin issue affecting the first element within the Container! Can you please provide an explanation for this anomaly?

Take a moment to check out this fiddle. In Container1 and Container2, the background color is set to #ccc, and h1 and .logo div have margins. While the left and right margins are working properly, the top and bottom margins are not functioning as expected. ...

Insert a JavaScript object into the rendered HTML using the componentDidMount lifecycle method

I'm trying to incorporate a JavaScript object into the template once the component has mounted for tracking purposes. Here is how I want the object to be rendered: var tracking = { pagename: 'page name', channel: 'lp&ap ...

Verify whether the template's form field is vacant

One issue I am facing is related to a form field named topics, which is a ManyToManyField. When calling {{form.topics}} in the template within a div inside a fieldset, I need to determine if the field is empty or if its length is less than or equal to 1. I ...

The function in JavaScript designed to load images before they are displayed is not functioning properly

Inside a custom object constructor, there is a method known as addToViewport(), which serves the purpose of displaying an image after it has been preloaded: window.onload = function(){ function ViewportObject(){ this.src = "ht ...

What is the best way to fetch Ajax information for use in several drop-down menus?

Is there a way to populate one multiple select drop-down based on the selection made in another multiple select drop-down using jQuery or ajax? Here is an example of how I am attempting to achieve this using ajax: function demo1() { var emp_id = docu ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Safeguard your contact information on the screen

On my classified website, I have concerns about the contact numbers being displayed as plain text in the product details page. This makes them visible to search engines. Is there a way to protect or display phone numbers as images to keep them hidden fro ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

A guide on incorporating search functionality and sorting options into DataTables

After setting up mySQL database and connecting it with PHP, I displayed the data on a webpage using AdminLTE and DataTables.net. Check out this tutorial that guided me through the process: The challenge I'm facing now is integrating the search box fu ...

"Utilize HTML to make inline-block elements appear small in size while giving the illusion of being

I have a group of inline-block elements (4 total), all arranged neatly in a single row. As the window size changes, the elements wrap to the next line accordingly. The page does not display scrollbars at the bottom until the browser width reaches the minim ...