You can do it with pure CSS and HTML, too. (Replace the links with checkbox inputs in that example, and include the tree in your form, and you're done.)
If you want to use Javascript, the standard technique is to generate the HTML for all input elements, just hide the ones that the user does not want/need to see right away, something like
where the subdir1 has to be unique across all ids on the page, and the Javascript function is something likePHP Code:
<div class="dir">
<input type="checkbox" name="files" value="dir1" onchange="subdir('subdir1', this.checked);"> dir1
</div>
<div class="subdir" id="subdir1" style="display: none;">
<div class="file">
<input type="checkbox" name="files" value="file1"> file1
</div>
</div>
and changes the nested div element visibility whenever the controlling checkbox state changes.Code:function subdir(id, visible) { document.getElementById(id).style.display = (visible) ? "block" : "none"; }
That does not work if the user reloads the page, as the display attributes reset to none, but the form contents stay unchanged. However, you can fix that by adding a body onload or onpageshow event, that checks all input elements in all forms on the page, and executes their onchange events explicitly.
The pure CSS+HTML option is a bit sensitive to browser versions, whereas the above Javascript stuff is trivial to implement in PHP (or other scripting languages). (In particular, you can use a fixed prefix plus an increasing integer for the id attributes.)
Using the familiar icons or suitable Unicode glyphs, it is not difficult at all to have the script produce a directory tree with quite intuitive collapse/expand/select semantics. In that case, I recommend using a dummy form and a hidden input field to list the expanded elements: that input field is retained over page reload, and you can reset the visibilities using its contents. Even with thousands of entries, this should work really snappy even on slow computers. (AFAIK, the browser memory use -- they're memory hogs! -- is what limits how large a tree you can use in a browser.)