How to Implementing jquery on Tree Checkbox (build from scratch - no plugin)
I don't know if the following Hierarchical Data is Adjacency list or Nested List model. What i know is, it's easy to collect the hierarchical data. For example,
to get all the tree then use : SELECT * FROM categories ORDER BY trn ASC
to get all the tree start from item News (7开发者_如何学运维) : SELECT * FROM categories WHERE trn LIKE '%+7+%'
It just a single query, instead of doing looping parent-child query.
catID cat_title status trn trn_level
7 News publish +7 0
8 Artikel publish +8 0
9 Public Training draft +7+9 1
10 Coorporate Mgt draft +8+10 1
16 MS Based On IS draft +7+9+16 2
17 Inhouse Training draft +7+17 1
18 MS publish +7+17+18 2
19 SM publish +7+17+19 2
So... my jQuery problem is: The datas above will produce checkbox html like the following :
News
Inhouse Training
MS
SM
Public Training
MS Based On IS
Artikel
Coorporate Management
<ul class="categoriesTree">
<li>
<?php str_repeat(" ",$row['trn_level']); ?>
<input type="checkbox" name="categories[]" value="<?php echo $row['catID']; ?>" class="<?php echo $row['trn']; ?">
<?php echo $row['cat_title']; ?>
</li>
</ul>
How to perform parent-child checked with jQuery. Example : if i checked on item News, i want it will also checked item - Inhouse Training - MS - SM - Public Training - MS Based On IS
Basicly i want to perform a parent child checked, if the child checked first, the the reference parent of the item will also checked, if the parent checked first then all the childs will checked.
I hope what I mean is clear enough :). I know that there are lots of tree plugin ready to use, but i want to understand & build my own from scratch.
Thanks in advance.
see this fiddle for an example. some explanations:
first:
class="<?php echo $row['trn']; ?"
that way you'll end up with class names like '+7', which are not valid in css.
as you don't have a proper hierarchy indication in your html yet (using a single UL), i'd recommend using the 'trn_level' field to build classes holding that information:
class="level_<?php echo $row['trn_level']; ?"
this will make it easier to determine the parent/child relationship for the checkbox logic. to simplify this some more, apply it to the 'LI' instead of the checkbox itself. this will also allow you to define css classes to do the indentation for you (instead of that hacky
stuff)
the jquery code for checking the checkboxes is quite straight-forward: find all preceding list elements, and check them in case their level is less than the current level. same thing is done for all next elements (having a level greater than the current one).
NOTE: for sure the code in my example could be simplified and tweaked some more, but in the end it's not a very elegant solution, as the hierarchy of the items isn't self-explanatory. you should really try to render nested UL's to reflect the hierarchy in HTML instead.
精彩评论