John Beasley John Beasley - 4 years ago 132
Javascript Question

JQUERY mark/stylize if dropdown selection is selected

I've been using JQUERY DATATABLES and I finally was able to add the "hide column" feature found here: https://datatables.net/examples/api/show_hide.html

However instead of using hyperlinks, I am using a button dropdown, as follows:

<div class = "btn-group">
<button type = "button" class = "btn btn-default btn-xs dropdown-toggle" data-toggle = "dropdown">
Hide Column
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a class="toggle-vis" data-column="1">Booking</a></li>
<li><a class="toggle-vis" data-column="2">Quote</a></li>
<li><a class="toggle-vis" data-column="3">Line</a></li>
...// and so on
</ul>
</div>


Here is the JQUERY that links the data-columns to the datatable and hides the column:

var table = $('#dataTable').DataTable();

$('a.toggle-vis').on('click', function(e) {
e.preventDefault();
var column = table.column($(this).attr('data-column'));
column.visible(! column.visible());

** EDIT **
$(this).toggleClass("dropSelected");
});


What I would like to do, is when one or more of the dropdown selections have been made (and the column has been hidden) is mark the selected dropdown with a check or change the color of the selection. This way, the user will immediately know which column has been hidden.

Of course, on the flip side, if the user clicks the link to make the column visible again, the check or color needs to disappear as the column will be visible again.

** EDIT **


Adding CSS to the top of the page:

a.toggle-vis.dropSelected {color: red;}

Answer Source

Given that all your columns start in visible state, and clicking a.toggle-vis changes their visibility, you can simply toggle the class of the element as such:

$('a.toggle-vis').on('click', function(e) {
   e.preventDefault();
   var column = table.column($(this).attr('data-column'));
   column.visible(! column.visible());

   this.toggleClass("hidden");
 });

And use CSS to cater for how a.toggle-vis.hidden is presented

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download