vendredi 1 juillet 2016

How to make a dynamic input tree in java script

Im trying to make somthing like this for a website

[category name (textbox)]
[add sub category (button to js function which creates sub category)]
[sub category field (textbox)]
[add sub category (button to js function which creates sub sub category)]
[sub-sub category field (textbox)]
[add sub category (button to js function which creates sub sub sub category)]

and so on...

so basically a large 'unlimited tree' where you can add as many categories, sub categories and sub, sub, sub, sub... categories as you want.

Here's what I have so far...

<body>
<script>
    var category = Array();
    var iter = 0;

    function addCategory(div){
        category[iter] = ["", 0];
        newElement = document.createElement('div');
        var content = '<input type="text" onchange="category[' + iter + '][0] = this.value">
                       <div id="new-sub" style="padding-left: 20px">
                          <button onclick="addSub('new-sub', ' + category[iter][1] + ', ' + iter + ')">Add Sub-category</button>
                       </div>';
        newElement.innerHTML = content;
        document.getElementById(div).appendChild(newElement);
        iter++;
    }

    function addSub(div, ID, iter){
        //here lies my confusion
    }

</script>
<div id="new-elements">
</div>
<button onclick="addCategory('new-elements')" >Add Element</button>
</body>

I the idea is to store the textbox values in an array as the user changes them. Only issue is I cant seem the get the multi-dimension array part right...

I'm an extreme beginner to JS, can anyone help me find a solution?

Aucun commentaire:

Enregistrer un commentaire