Toggle visibility of column in table using cookies

I was looking to store user preferences for shown/hidden columns in the browser using cookies, so that the table layout wouldn't reset upon page refresh.

Fiddle : http://jsfiddle.net/HvA4s/72/

HTML

<a href="edit" id=edit>Show/Hide Columns</a>
<table id=table>
<thead> 
    <tr>
        <th id="name">Name</th>
        <th id="street">Street</th>
        <th id="number">Number</th>
    </tr>
</thead> 
<tbody>
    <tr>
        <td>Freddy</td>
        <td>Nightmare Street</td>
        <td>123</td>
    </tr>
    <tr>
        <td>Luis</td>
        <td>Lost Street</td>
        <td>3456</td>
    </tr>
</tbody>
</table>

Jquery

$('#edit').click(function() {
    var headers = $('#table th').map(function() {
        var th =  $(this);
        return {
            text: th.text(),
            shown: th.css('display') != 'none'
        };
    });

    var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
    $.each(headers, function() {
        h.push('<th><input type=checkbox',
               (this.shown ? ' checked ' : ' '),
               '/> ',
               this.text,
               '</th>');
    });
    h.push('</tr></thead></table></div>');
    $('body').append(h.join(''));

    $('#done').click(function() {
        var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
        $.each(showHeaders, function(i, show) {
            var cssIndex = i + 1;
            var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
            if (show)
                tags.show();
            else
                tags.hide();
        });

        $('#tableEditor').remove();
        return false;
    });

    return false;
});

If I hide column 1 and column 2 using the button, they reappear upon page refresh. Is there a way to utilize cookies to maintain these settings until manually changed again using the same options?

Answer №1

To accomplish this task, you can utilize the jquery.cookie plugin:

$('#table th').each(function ($index, $elem) {
    var $cookie = $.cookie(this.id.toLowerCase() + ".shown");
    $index = $index + 1;
    $('#table th:nth-child(' + $index + '), #table td:nth-child(' + $index + ')').css('display', (typeof ($cookie) === "undefined" || $cookie === "true") ? "" : "none");
});

$('#edit').click(function () {
    var headers = $('#table th').map(function () {
        var th = $(this);
        var $cookie = $.cookie(th[0].id + ".shown");
        return {
            text: th.text(),
            shown: th.css('display') != "none"
        };
    });

    var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
    $.each(headers, function () {
        var $shown = this.shown;
        h.push('<th><input type=checkbox', ($shown ? ' checked ' : ' '),
            '/> ',
        this.text,
            '</th>');
    });
    h.push('</tr></thead></table></div>');
    $('body').append(h.join(''));

    $('#done').click(function () {
        var showHeaders = $('#tableEditor input').map(function () {
            return this.checked;
        });
        $.each(showHeaders, function (i, show) {
            var cssIndex = i + 1;
            var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
            var $id = $('#table th:nth-child(' + cssIndex + ')')[0].id;

            if (show) {
                $.cookie($id + ".shown", "true");
                tags.show();
            } else {
                $.cookie($id + ".shown", "false");
                tags.hide();
            }
        });

        $('#tableEditor').remove();
        return false;
    });

    return false;
});

Check out the updated fiddle here

Answer №2

JSfiddle Check out the JSFiddle demo here.
HTML Table Header Show/Hide Tutorial

**HTML **
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">   </script>
</head>
<body>
<table  border="1">
  <thead>
    <tr>
        <td> Cell 1 <i Title="Hide" class="fa tbtn fa-times">X</i></td>
        <td>Cell 2 <i Title="Hide" class="fa tbtn fa-times ">X</i></td>
        <td>Cell 3 <i Title="Hide" class="fa tbtn fa-times">X</i></td>
    </tr>
</thead>
<tr class="del">
    <td>Row 0 Column 0</td>
    <td>Row 0 Column 1</td>
    <td>Row 0 Column 2</td>
</tr>
<tr class="del">
    <td>Row 1 Column 0</td>
    <td>Row 1 Column 1</td>
    <td>Row 1 Column 2</td>
</tr>
<tr class="del">
    <td>Row 2 Column 0</td>
    <td>Row 2 Column 1</td>
    <td>Row 2 Column 2</td>
</tr>
<tr class="del">
    <td>Row 3 Column 0</td>
    <td>Row 3 Column 1</td>
    <td>Row 3 Column 2</td>
</tr>
<tr class="del">
    <td>Row 4 Column 0</td>
    <td>Row 4 Column 1</td>
    <td>Row 4 Column 2</td>
</tr>
<tr class="del">
    <td>Row 5 Column 0</td>
    <td>Row 5 Column 1</td>
    <td>Row 5 Column 2</td>
</tr>
</table>
<button id="show"> Show all</button>
</body>


</html>

Jquery $(document).ready(function () {

    $("thead td .tbtn").click(function () {

        caaell = parseInt(this.parentElement.cellIndex + 1);
      //  alert(caaell);
        $('td:nth-child(' + caaell + ')').hide();
    });

    $("#show").click(function () {         
        $('td').show();           
    });
});

CSS .tbtn { cursor:pointer; float:right; padding:3%; font-size: 13px; font-family: monospace;

}
    .tbtn:hover {
    opacity:0.5;
    }
thead{
      background: #184a74;
color: white;

}

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

The value returned by a component should remain consistent regardless of where it is invoked. Additionally, the main component in React should not re-render when the state of a sub-component is

I am looking to have the same value displayed in the Home function from the Component, without causing a rerender when the useState in Component is updated. import { useState, useEffect } from "react"; function Component() { const [count, setC ...

Revamp Child Relationship in Ruby on Rails Form

One of the challenges I'm facing is with editing and updating priorities for parent accounts in my application. The "Accounts" model acts as the parent, while the "Priorities" model serves as the child. Creating new priorities for these accounts is s ...

Converting TypeScript to JavaScript in a React JS application: Steps and best practices

As a beginner in the world of React, I am currently struggling with transitioning from TypeScript to JavaScript The code snippet below demonstrates the use of table filter with TypeScript. How can I adapt this code to utilize JavaScript instead? Click he ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

The hyperlink within the dropdown menu in HTML code is malfunctioning

I'm currently working on my personal website using HTML and CSS with textedit. I've successfully created functional links for the main navigation menu headings, but I'm encountering issues with the dropdown options. Whenever I try to click o ...

Retrieving data from PHP using jQuery and JSON

Struggling to retrieve various variable outcomes from PHP using jQuery JSON. Encountering issues with null values appearing in the console (like in the title), causing script failures. Currently, attempting to fill input fields with data received from PHP. ...

What is the best way to incorporate two range sliders on a single webpage?

I recently started using rangeslider.js on my webpage. I wanted to convert two input fields into range sliders, so I began by converting one successfully. Initially, the HTML code looked like this: <div class="rangeslider-wrap"> <input type=" ...

HTML and CSS: Centering elements inside div containers

Is it possible to align elements within a </div> using the align attribute? For example, as shown in the image below: e1:align="top" e2:align="right" e3:align="bottom" e4:align="left" EDIT: This query is purely for self-learning purposes in HTML ...

What is the best way to verify the presence of values in a table row?

I am having some difficulty finding the correct solution for what I am trying to achieve. Here is the code snippet: var _1 = "Something1"; var _2 = "Something2"; var result = "dsadas"; $('<tr><td>' + _1 + '</td><td> ...

Execute a sorted operation with proper authorization

Recently, I developed a NextJs dashboard that enables Discord users to connect to their accounts. One of the main features is retrieving the user's guilds and filtering them to include only the ones where the user has either the MANAGE_GUILD permissio ...

Deleting empty tags in an HTML h1 element with JavaScript

Is there a way to use JavaScript to remove empty h1 tags only? <h1>Hello World!</h1> <p>Lorem ipsum dolor sit amet</p> <h1></h1> <p>consectetur adipiscing elit.</p> <h1></h1> <p>Sed do ...

What sets Angular Material apart from AngularJS Material when it comes to responsiveness?

I am facing a dilemma in choosing a framework for my application. In my search, I came across Angular Material and AngularJS Material. Although both frameworks are developed by Google (correct me if I'm wrong), they seem to serve the same purpose of r ...

Problem with accessing state in React 16

In my code snippet below, I am encountering an issue. When the button is clicked and 'streaming' appears on the UI, the console.log within the 'process' function displays false. Can you help me identify what might be causing this discre ...

Connecting JavaScript and PHP strings

My goal is to transfer a JavaScript string to a PHP processing script and compare them. Upon successful match, I intend to conduct a simple validation process and if it passes, send an email notification. To provide context, below is a snippet of my curre ...

JavaScript Thumbnail Slider Builder

I've been working hard on developing a custom JavaScript thumbnail slider that uses data-src. Everything seems to be in order, except the next and previous buttons are not functioning properly. Any assistance would be greatly appreciated. Here's ...

There seems to be an issue with the VueJs + ElementUi Change method as it is

Just starting out with Vue and Element UI. I'm attempting to create a custom component using the ElementUI autocomplete/select feature. The problem I am facing is that the @change method does not contain a event.target.value value. When I try to acc ...

React - A guide on accessing the scroll position of a div using JavaScript

Within my side navigation bar, there is a title and other information. The title is fixed in place (sticky) and the sidebar has a height of 100vh. I am looking to add a box-shadow effect to the title div (sticky-title) only when the user scrolls down past ...

Implementing es6 syntax for overloading a library class

In my project, I have various objects that extend other objects from a library. The library object extends the Object class of the library. Therefore, the architecture is as follows: // The library object class class Object { } // The library object1 c ...

Troubleshooting: Next.js - Issues with encodeURIComponent function when using `/` in getStaticPaths

Reproducible site showcasing the issue: Reproducible code example: https://github.com/saadq/nextjs-encoding-issue Homepage Food page The goal is to dynamically create static pages for different food items based on their titles. This functionality works ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...