I need to provide users with the ability to hide/show table columns. Using previous examples with my own adjustments i have used checkboxes to hide/show columns, but now need to remove form elements.
I’m very new to jquery/javascript so hoping someone can help with info on now how to
1. Hide some columns on load (based on trigger in code)
2. Swap images when column is toggled to give users visual feedback as to which columns are shown/hidden.
I have a fiddle at
http://jsfiddle.net/IllusionVK/DqQFP/14/ which has the following code in it:
Previously used following code
$("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();
});
});
but had to remove form elements (checkboxes), and am now trying to use img tag in place of checkbox:
$('img').click(function(){
var column = $(this).attr('id');
$('td:nth-child('+ column +')').toggle();
});
I’m hoping that the final code will be useful for all to hide/show columns without needing to add any code to the actual tables and is using nth-child dynamically.
Any help would be very much appreciated!! Cheers, Charlie.
Sources of help so far:
http://www.devcurry.com/2009/07/hide-table-column-with-single-line-of.html
Uses nth-child, BUT is hardcoded, and designed for only one column show/hide
hide table columns automatically by checking a checkbox with jQuery
But requires that table is overburdened with extra classes=bad for me, use checkboxes=also bad
If you use index() you should be able to dynamically show/hide columns if you make a convention that your text of your tags match the table header tags.
Updated jsfiddle.
side note, a img element can’t have text
<img>text</img>, so I adjusted the list to use a span tag instead.update
If you want to easily toggle the legend items you could do something like this..
And the following css:
And your jquery could toggle the class to change the background-image
If you want to hide columns on page load simply add a uncheck class to the legend div you want to uncheck.
Then running this script will trigger which ones to uncheck.
Example on jsfiddle.