views:

51

answers:

3

Hello, I have a tree view based on < ul > and < li > tags.

I am trying to hide the branches based on filter text. Here is my show/hide code:

$("#filter").change(function(){
       var tval=$(this).val();
       $("li").show();
       $("li").not(":contains(\'"+tval+"\')").hide();
       $("li").is(":contains(\'"+tval+"\')").show();

       })

The command: $("li").is(":contains(\'"+tval+"\')").show(); shows branches filtered by given tval, but if given < li > has a further children I would like to show them as well. How can I show all child elements if they exist?

kind regards Arman.

EDIT

example: search text A and we have D=>A=>C, D=>C=>C, A=>K=>S, so after filtering my tree should be: D=>A=>C, A=>K=>S. In the current implementation it will look like D=>A, A

+1  A: 

You can simplify your approach a bit like this:

$("#filter").change(function(){
   var tval=$(this).val();
   $("li").hide().filter(":contains('"+tval+"')").find('li').andSelf().show();
});

This hides all <li> elements, then shows if they directly contain the value (or are a parent that contains it)...and for those also shows all descendant <li> elements, showing all children hopefully like you want.

Nick Craver
Thanks, nice suggestion, but what about <ul> elements?
Arman
@Arman - Your original code was just hiding the `<li>` so that's all you need to show...if you're hiding them separately, do `.find('ul, li')` instead of the `.find('li')` I have above so it'll show those too :)
Nick Craver
Much better solution than mine!
jarrett
A: 

If I understand correctly the child selector is what you want.

jerone
That does not solve my problem. The next child can be ul or li how can I proceed that?
Arman
can you post a example of how the tree looks like...
jerone
Yes, I just added EDIT in my post.
Arman
A: 

Try this

$("#filter").change(function(){
       var tval=$(this).val();
       $("li").hide();
       if(tval != ""){             
         $("li").each(function() { 
           if($(this).is(":contains(\'"+tval+"\')")){ 
             $(this).show().find('li').show();
           }
         });
       }
       else {
         $("li").show();
       }
})

So hide all of them, then look for matches and then for each matched li show it and all child li

EDIT: Edited again, sorry I totally missed it last time

jarrett
Thanks for the code, if I try it then all tree is stays hidden. The problem from FireBug is: $("li").is(":contains('" + tval + "')").show is not a function
Arman
also, contains() is case sensitive, you can use a regex if you don't want that
jarrett
Yes, even with case sensitive it blends all values. I just found simple solution for the moment I am filtering tree on server side with SELECT * FROM tree_view WHERE branches LIKE '%$filter%'.
Arman