I have to show only selected nodes and parents, and hide rest nodes when a button is clicked. Only nothing happens when I click the button.
The jsfiddle
The code with commenting
start on button click
$('button[name="psychTree-selected"]').click( function(node) {
get the selected nodes
nodesSelected = $('#psychTree').tree('getSelectedNodes');
create an array for shown nodes
nodeIdsToStay = [];
walk through selected nodes
nodesSelected.forEach( function(node) {
var path = $('#psychTree').tree('getData');
path.forEach(function(n) {
if (nodeIdsToStay.indexOf(n)===-1) {
nodeIdsToStay.push(n);
}
})
})
hide the nodes not in the array
$('#psychTree').find('li').each( function(){
if ( nodeIdsToStay.indexOf(this.id) === -1 ) {
$(this).hide();
}
})
})
I know how to hide the selected nodes but apparently non selected nodes do not have an identifiable class for me to search and hide by http://jsfiddle.net/tom1nkfr/
`$('button[name="psychTree-selected"]').click( function() {`
`$('#psychTree').find('.jqtree-selected').each( function(){`
`$(this).hide();`
`})`
`})`
I'd recommend a simpler approach - it looks like you're trying to find all the nodes that are selected, push those into an array
, then iterating over the entire jsTree and hiding any nodes not in the array
you created. Instead, leverage the CSS classes that jsTree is already applying to selected nodes and just hide all those that don't have it.
Simplified JS:
$('button[name="psychTree-selected"]').click(function() {
$('#psychTree li.jqtree_common').each(function(index,elem){
if(!$(elem).hasClass('jqtree-folder') && !$(elem).hasClass('jqtree-selected')){
$(elem).hide();
}
});
})
Still triggered on your button click, but now it iterates through all the tree nodes and hides any that are (1) not selected and (2) not parent/folder nodes.
Working JSFiddle: http://jsfiddle.net/tbwjau5m/