I'm working on something at the minute that is giving me a lot of grief. Basically I'm using bootstrap and jQuery to design a webpage and its got to the point where I'm sending JSON over the network to save to a hibernate back end. All of the objects are set up fine and are working, but I'm looking for a "better" solution to generate the array than the one I've currently got. The relationships are like this:
Parent -> Child -> GrandChild
`-> Child -> GrandChild
All of the mappings are one to many relationships, and the way the divs are laid out on the screen is basically like this:
<div id="left">
<div id="parent"></div>
<div id="Child"></div>
<div id="GrandChild"></div>
</div>
<div id="right">
<div id="Child"></div>
<div id="GrandChild"></div>
</div>
(again you can have many "Child" divs, and many "GrandChild" divs between each "Child" div, and the same for the right side - the nesting actually goes deeper than this, but if I can figure out this to start with then I can adapt it). What I am doing at the minute is when the user presses "Save" is to build the tree by renaming the name element of every input in every div in order for the mapping to work when I seriallize the whole page. What I am finding is that this requires a horrendous function to essentially loop through all of the divs and reset counters whenever a new parent object is encountered. For example assume (on the left side):
<div id="left">
<div id="Parent"></div>
<div id="Child"></div>
<div id="GrandChild"></div>
<div id="GrandChild"></div>
<div id="GrandChild"></div>
<div id="Child"></div>
<div id="GrandChild"></div>
</div>
My javscript would essentially do this (pseudocode):
childCounter = -1;
grandChildCounter = -1;
for each div {
if div == Parent { skip };
if div == Child { childCounter +=1; grandChildCounter = -1; childDiv.name = childArray[childCounter] };
if div == GrandChild { grandChildCounter += 1; grandChildDiv.name = childArray[childCounter].grandChildArray[grandChildCounter] };
}
Obviously with more nested levels this kind of code just gets insane... so I've been trying to generate the array recursively by building everyone's children beforehand and appending it to the object as an array - but I run into the same issue of needing manually traverse down the nest just to append the array of children to their correct parent. Either way seems cumbersome and produces really sloppy code - I am new to javascript and jQuery so I do wonder if I'm going about this whole thing the wrong way and am looking for some advice.
It's worth noting that the whole thing is dynamic, and the addition of new divs in the correct order based on pressing buttons on the page already works perfectly. The tree HAS to be generated when the user presses save.
I'm also sorry about the lack of proper code but the work isn't at home. Thanks in advance
grandchildalways belongs to the last instance of achild.