Alternative way to pass checkbox value in DynaTree

alternative way to pass checkbox value in dynatree Projects

Learn how to combine dynatree (javascript tree widget) and a normal form to send selections to a server

What is dynatree?

Dynatree is a JavaScript dynamic tree view plugin for jQuery with support for lazy loading of branches. Created and maintained by Martin Wendt. Most important features:

  • Lazy loading using Ajax
  • Checkboxes for selections
  • Theming
  • State persistence with cookies
  • Context menu
  • Copy/paste of nodes

Problem description

I had to create a tree widget using Archetypes. I’ve done some research and selected Dynatree as the best solution for me. It had all the features and used jQuery. But then I’ve discovered that checkboxes are not real checkboxes. They are just images that are manipulated by changing CSS using jQuery. That was a small surprise because I had to send a selection in a form and save it. But there was no real input fields.

I came up with a solution to this problem. After few suggestions from the author I’ve written some HTML and jQuery code to fulfill my needs. I’ve added normal checkboxes and javascript to select and deselect them as appropriate.

Check example of dynatree with checkboxes straight away or read more information below.

DIY – do it yourself

Example presented here shows general use case. It has nothing to do with Plone and Archetypes. Maybe this is a subject for next article.

HTML code

This one is easy. I’ve added fields with a prepared id attribute that contains node id and a prefix.

Javascript (jQuery) code

Above there is a snippet of jQuery code that does all the tricks. First we’ve defined 4 parameters for our dynatree. Please refer to Dynatree documentation for more explanation. Secondly we’ve added 2 events: onSelect makes sure that real checkboxes (hidden) are checked and unchecked together with their image counterparts; onExpand goes around a problem with showing up hidden checkboxes when node is collapsed or expanded. Then we’ve dynamically assigned CSS class to hide checkboxes. Lastly we’ve added code that initializes checkboxes when the page is loaded again and state is read from cookie.

Check here for example of dynatree with checkboxes that can be send in a form. View underlying HTML to see above code in context.

If you want to know more about amazing jQuery see the latest books:

Alternative way to pass checkbox value in DynaTree

I have done this like below, just get list of selected nodes and pass in hidden field comma separated values:

var selectedNodes = $(“#tree”).dynatree(“getTree”).getSelectedNodes();

Rate article
Plone and Zope developer
Add a comment