daweilv / treejs

A lightweight tree widget, compatible with VanillaJS / React / Vue. Tiny size after gzip. Zero dependence.
MIT License
142 stars 49 forks source link

Submit Checkboxes to form #31

Open trymeouteh opened 1 year ago

trymeouteh commented 1 year ago

Is it possible for the tree to use checkboxes to allow for the tree values to be submitted in a form?

THenkeDE commented 1 year ago

you could easily do that using the onChange method of the tree itself:

html:

<form ...>
    <input id="selectednodesformfield" type="hidden" name="selectednodes" />
</form>

js:

    let selectedNodes = [];
    let tree = new Tree('<selector>', {

        ...,
        onChange: function() {
            selectedNodes = [];
            this.selectedNodes.forEach( function(node){
                selectedTree.push(node.id);
            });
            document.getElementById('#selectednodesformfield').value = JSON.stringify(selectedNodes);
        },
        ...
    });

Now you have an JSON encoded string of all node Ids in a formfield and you can work with that at the target of your form submission.