Lazy AJAX with checkbox problem


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:

jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer Learning jQuery 1.3 by K Swedberg and J Chaffer

Lazy AJAX with checkbox problem

I am trying in integrate lazy AJAX with your checkbox solution and i have one problem.
Every time i press the plus sign and a new branch is expanded with data out of the database all of the checkboxes that where previously selected on a different branch are cleared.

Rate article
Add a comment