I read a lot of posts about saving cookie and reading from it but none has worked for me. I have a grid of 42 columns and I would like to achieve the following:
- Be able to hide/show columns using checkboxes on a pop-up window (bootstrap modal) (achieved)
- save the result in a cookie and read from it next time I visit the page.
What's different about my question is the way I populate those checkboxes which makes reading a cookie and applying .hide a little different:
$(document).ready(function () {
var shown = false;
//edit table button shows a bootstrap modal
$('#edit').click(function () {
//getting table headers
var headers = $('#entryTable thead th').map(function () {
var th = $(this);
return {
text: th.text(),
shown: th.css('display') != 'none'
};
});
var h = ['<div id=\"tableEditor\"><table><thead>'];
$.each(headers, function () {
h.push('<tr><th style=\"width:150px;\"><input class=\"box\" type=checkbox name=\"' + (j) + '\"',
(this.shown ? ' checked ' : ' '),
'/> ',
this.text,
'</th></tr>');
});
h.push('</thead></table></div>');
//show modal on #edit click and append the checkboxes into modal body
$('#myModal').modal('show');
$('#myModal').on('shown.bs.modal', function () {
if(!shown)
$('#myModal').find('.modal-body').append(h.join(' '));
shown = true;
});
$('#checkAll').click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
//apply .hide property to unchecked columns
$('#Apply').click(function () {
var showHeaders = $('#tableEditor input').map(function () { return this.checked; });
$.each(showHeaders, function (i, show) {
var cssIndex = i + 1;
var tags = $('#entryTable th:nth-child(' + cssIndex + '), #entryTable td:nth-child(' + cssIndex + ')');
if (show)
tags.show();
else
tags.hide();
});
return false;
});
return false;
});
//saving in cookie
$("input.box").each(function () {
var myCookie = $.cookie($(this).attr('name'));
if (myCookie && myCookie == "true") {
$(this).prop('checked', myCookie);
}
});
$("input.box").change(function () {
$.cookie($(this).attr("name"), $(this).prop('checked'), {
path: '/',
expires: 365
});
});
function repopulateCheckboxes() {
var checkboxvalues = $.cookie('myCookie');
Object.keys(checkboxValues).forEach(function(element) {
var cssIndex = i + 1;
var tags = $('#entryTable th:nth-child(' + cssIndex + '), #entryTable td:nth-child(' + cssIndex + ')');
if (show)
tags.show();
else
tags.hide();
});
}
repopulateCheckboxes();
});
I am sure of everything I do before the cookie part. It works perfectly but not sure how to do the rest. What am I doing wrong?
Thanks so much in advance
Aucun commentaire:
Enregistrer un commentaire