JSTree with Datatables - javascript

I have two columns on a page, with a checkbox jstree on the left and a table using datatables on the right. The table rows and tree are all loaded at startup.
I would like to show a row when the node is selected on the tree and hide the row when its unchecked and I'm using a class for this. I am having problems with looping though all the rows in a datatables and setting a class, so I can filter it. This is the code I'm using below, but its not working. I can't get any id for the table row.
table.rows().iterator( 'row', function ( context, index ) {
var tableNode = $(this.row(index).node());
tableNode.removeClass('VisibleRow').removeClass('HiddenRow').addClass('HiddenRow');
var id = tableNode.id;
var treeNode = data.instance.get_node(id);
if(treeNode != undefined){
var currentId = '#row-' + node.id;
var rowInTable = table.row(currentId).node();
$(rowInTable).removeClass("HiddenRow");
$(rowInTable).addClass("VisibleRow");
}
});
Let me know if there are better ways to do this.

I believe you can do it with the snippet below. The rows iteration is jQuery based, there is no DataTables-specific logic there.
Also check demo - Fiddle Demo
var $tableRows = $('#yourTableId').find('tr');
$('#yourTreeContainer').on('select_node.jstree', function(e, data) {
$tableRows.each(function() {
if (this.id === '#row-' + data.node.id) {
$(this).removeClass('HiddenRow');
} else {
$(this).addClass('HiddenRow');
}
});
});

I created same with some changes and it works fine, but even with hidden row I don't want datatable showing empty pages. Any advice, please?
this my code
$('#jstree')
.jstree({
core: {
data: treeData
},
checkbox: {
three_state : false, // to avoid that fact that checking a node also check others
whole_node : false, // to avoid checking the box just clicking the node
tie_selection : false // for checking without selecting and selecting without checking
},
"plugins" : ["checkbox","conditionalselect"]
})
.on("check_node.jstree uncheck_node.jstree", function(e, data) {
$tableRows.each(function(){
//$(this).addClass('HiddenRow'); //should not be there
if( this.id === data.node.id ) {
if(data.node.state.checked ){
//alert("removeClass");
$(this).removeClass('HiddenRow');
}else{
//alert("addClass");
$(this).addClass('HiddenRow');
};
}else{
}
})
})
This is the link http://jsfiddle.net/cf7tata9/56/#&togetherjs=jqPTfx3gpk

Related

Isotope v2 Grid - Multiple Filters - Hide empty filters

My current isotope grid has two dropdown filters that sort the grid items. The first filter is menu type, and the second filter is drink type. Each menu type however does not contain all drink types so when some filter configurations are chosen, no results are showed, which is correct. But i would like to stop this from happening by when the user selects the first filter, the second filter hides the empty types.
Working Codepen of current filters: https://codepen.io/whitinggg/pen/zYGEaNb
This was my old filter code:
// Select Filters
jQuery(function ($) {
var $grid = $('.grid');
var $selects = $('div#filterGroup select').change(function() {
var selector = $selects.get().map(function(el) { // map the select elements ...
return $(el).val(); // ... to an array of values
}).join('') || '*'; // if joined array is empty-string, then default to a single '*'
$grid.isotope({
'filter': selector
});
return false;
});
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
});
I have tried to change my code to the below from other links around the internet on this topic but havent had any luck getting it to work.
// Select Filters
jQuery(function ($) {
var $grid = $('.grid');
var $selects = $('div#filterGroup select').change(function() {
var selector = $selects.get().map(function(el) { // map the select elements ...
return $(el).val(); // ... to an array of values
}).join('') || '*'; // if joined array is empty-string, then default to a single '*'
$grid.isotope({
'filter': selector
});
return false;
});
//Hide Empty Filters
var DROP = $('div#filterGroup select option:not([data-filter=""])');
// list of all class in html
var strall = ''; $('.grid-item').each(function(el){ strall += $(this).attr('class') });
// remove select if not in strall.. TODO : needs improvement, this is kind a hack
DROP.each(function(el){
var nowfilter = $(this).attr('data-filter').replace('.', ''); // co_kenya
if( strall.indexOf( nowfilter ) == -1 ){
console.log( 'this one is missing ' + nowfilter );
$(this).remove();
}
});
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
});
Is this possible? Any help much appreciated!
Working codepen
First, add an ID to each drop-down so that we can distinguish them.
<select id="menu-selector" class="filter option-set" data-filter-group="menu">
[...]
<select id="type-selector" class="filter option-set" data-filter-group="categories">
Then, for each drop-down, add a change listener. We'll look at the code for the menu drop-down change listener.
First, get the class filter from the selected drop-down:
$('#menu-selector').change(function() {
var selectedClass = $('#menu-selector option:selected').attr('value');
Then we're going to select all of the grid items matching that type, to see what other classes they have. These other classes will be the available types
var availableTypes = $(`.grid-item${selectedClass}`)
.toArray()
.flatMap(div => Array.from(div.classList.values())) //get all of the classes
.filter(i => !['grid-item', selectedClass.substring(1)].includes(i)); //eliminate useless ones
Last, toggle the disabled property on the other drop-down, enabling only those that are available.
$('#type-selector option')
.each( (i,el) => $(el).prop('disabled', el.value != "" && !availableTypes.includes(el.value.substring(1))));
That should do it. The change handler for the type drop-down is the same but references the opposite drop-down. Check the codepen for details.

How to get value from DataTables row on row click event

I have a HTML page with a DataTable (datatables.net) with data that is populated from the database. What I'm trying to accomplish is to be able click on a row in the datatable and when it's selected, store an ID value contained in the datatable into an array for later use. If a particular row is unselected, the array would be searched, and the matching ID value would be removed. Here is what I have tried so far. It seems to work sporadically:
$('#businessTable tbody').on('click', 'tr', function () {
var data = BusinessFileTable.row({ selected: true }).data();
if ($(this).hasClass('selected') == false) {
FullBusinessRecordIDs.push(data.BusinessID);
} else {
var index = FullBusinessRecordIDs.indexOf(data.BusinessID);
if (index > -1) {
FullBusinessRecordIDs.splice(index, 1);
}
}
});
Any suggestions on what I can do to improve on it? Does anyone know of a sample out there?
I think you should use the select extension and rebuild FullBusinessRecordIDs on each select / deselect event :
var FullBusinessRecordIDs = [];
$('#example').on('select.dt deselect.dt', function() {
FullBusinessRecordIDs = [];
table.rows({ selected: true }).every(function() {
FullBusinessRecordIDs.push( this.data().BusinessID )
})
//how as demo string
$('#ids').val( FullBusinessRecordIDs.toString() )
})
demo -> http://jsfiddle.net/4rnsq28s/

toggle row with specific attribute in jquery datatable on click

I'm new to jquery datatable.
What I'm trying to achieve is, to toggle(hide/show) the row of datatable which is having attribute named status_id with value 9 to 13 on button click.
I have tried this for only number 9, but it's not working.
var dTable = $('#tbl_taskList').DataTable();
$(document).on('click', '.hide-tasks', function (e) {
e.preventDefault();
var row = dTable.row($(this).attr('status_id'));
if(row === '9') {
dTable.row().hide();
}
});
There is no hide() feature for rows. Basically is what you are trying to do a specialized filter, so you could create a custom filter to achieve what you want. Here is an example of a toggleable filter which hide or shows <tr>'s with status_id 9 or 13 :
$('#hide-tasks').on('click', function (e) {
//is the checkbox checked?
if ($(this).is(':checked')) {
//add filter
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
//always go through the API when working with dataTables!
var status_id = parseInt(table.row(dataIndex).nodes().to$().attr('status_id'))
return !~[9,13].indexOf(status_id)
})
} else {
//reset filter
$.fn.dataTable.ext.search.pop()
}
//update table
table.draw()
})
demo -> http://jsfiddle.net/k1cz6rma/
Datatables docs says table.row hasn't hide fucntion but row().child() does.
var row = dTable.row(':eq('+$(this).attr('status_id')+')');
row.child().hide(); // hides
row.child().show(); // shows
checkout this page
row().child().hide()

Some questions around clone/copy TR

I have this code for clone/copy a tr element from a modal to a page.
$(function () {
$('#toggleCheckbox').on('click', function () {
var $toggle = $(this).is(':checked');
$("input:checkbox").attr('checked', $toggle);
$('#btnAplicarNorma').prop('disabled', !$toggle);
});
$('#resultadoNormaBody').on('change', 'input[type=checkbox]', function () {
var $my_checkbox = $(this);
var $my_tr = $my_checkbox.closest('tr');
if ($my_checkbox.prop('checked')) {
$my_tr.addClass('copyMe');
}
var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]');
$all_checkboxes.each(function () {
if ($(this).prop('checked')) {
$('#btnAplicarNorma').prop('disabled', false);
return false;
}
$('#btnAplicarNorma').prop('disabled', true);
});
});
$('button#btnAplicarNorma').on('click', function (ev) {
var $tr_to_append = $('#resultadoNormaBody').find('tr.copyMe');
$('#tablaNorma').removeAttr('style');
$('#alertSinNorma').hide();
if ($tr_to_append.length) {
$tr_to_append.find('input[type=checkbox]').prop('checked', false);
$tr_to_append.clone().appendTo('#normaBody').removeClass('copyMe');
$tr_to_append.removeClass('copyMe');
$(this).prop('disabled', true);
}
});
});
But I'm having some issues:
If I mark all checkboxes using the first on the table head then I the code stop working and doesn't clone any tr even if all of them are marked
How do I avoid to clone/copy the same tr twice?
It's possible to modify the checkbox before clone it? If you take a look at the example you'll notice how the clone tr copy exactly as the one on the modal and I want to uncheck the checkbox first, it's possible?
Here is a fiddle to play with, any advice?
The main problem is that your checkboxes inside the table do not really get properly triggered when you programmatically set them selected. To make sure all associated Events get properly triggered you should be triggering a .click() event instead:
$("#resultadoNormaBody").find("input:checkbox").click();
to ensure that you don't end up with duplicate clones the easiest thing is to not clone all the rows in one batch, but iterate thru them, and comparing the html to the ones that have already been added like this:
//fetch all the rows that have already been cloned
var clonedRows = $("#normaBody").find("tr");
//iterate thru all the rows that have been checked
$.each($tr_to_append, function (i, v) {
var added = false;
//fetch their html (for easier compare)
var currentRowHtml = $(v).html();
//now compare against the rows that have already been cloned
$.each(clonedRows, function (i, cRow) {
var clonedRowHtml = $(cRow).html();
if (currentRowHtml == clonedRowHtml) {
added = true;
}
});
//if the row hasn't been added yet- go ahead and clone it now
if (!added) {
$(v).clone().appendTo('#normaBody').removeClass('copyMe');
}
});
Here's a link to your updated fiddle:
http://jsfiddle.net/wq51zL9x/4/
Here is some more info on comparing table rows: Compare two tables rows and remove if match
and here's the more elaborate answer to using .click()
Need checkbox change event to respond to change of checked state done programmatically

How to get the selected check boxes in Kendo Mobile

I'm new to kendo I have a list populated from a data source (with template : Each list item has mobile switch in it).I need to get all the id's of selected mobile switches when I clicked on a single button. Can anyone let me know how to do that in kendo ?
Cheers,
Chinthaka
I solved that Using following code (Only Active Items checked items)
var checkedWorkCentersIds = new Array();
$('#workcenters :checkbox:checked').map(function () {
if (this.checked == true) {
checkedWorkCentersIds.push(this.id);
}
});
Without the code it is hard to give an exact answer, but you should be able to just loop over the data items in the array and find the ones that are selected.
For example:
var dataSource = new kendo.data.DataSource( ... );
function getSelected() {
return $.grep(dataSource.view(), function (item) {
return item.selected;
});
}
Assuming the switches/checkboxes are bound to the "selected" property.
In response to your comment, you can get the selected checkbox element IDs with jQuery:
$("#workcenters :checkbox:checked").map(function (index, checkbox) {
return $(checkbox).attr("id");
});

Categories

Resources