orugari orugari - 2 months ago 17
jQuery Question

Serialize from ul li with child using jqueryui sortable

I would like to know how to create a JSON or serialize (both is fine) from a ul including

<ul class="menu send ui-sortable">
<li id="pageid_1" class="ui-sortable-handle">Inscription
<ul class="menu send ui-sortable">
<li id="pageid_2" class="ui-sortable-handle">Joueurs en ligne
<ul class="menu send ui-sortable"></ul>
</li>
</ul>
</li>




I cannot find how to create something like this:

pageid[]=1&pageid[1]=2
OR
[{"pageid":1,"children":[{"pageid":2}]}]


Meaning, including parent ID in
[]
.

Thank you for your help!

Answer

This code will produce the output required

var result = [].map.call(document.querySelectorAll('ul.menu.send.ui-sortable li.ui-sortable-handle'), function(li) {
    var parent = '';
    if (li.parentNode && li.parentNode.parentNode && li.parentNode.parentNode.nodeName == 'LI' && li.parentNode.parentNode.matches('li.ui-sortable-handle')) {
        parent = li.parentNode.parentNode.id.replace(/\D+/g, '');
    }
    return "pageid[" + parent + "]=" + li.id.replace(/\D+/g, '');
}).join('&');
console.log(result); // pageid[]=1&pageid[1]=2

I haven't thought about how to do the second format, because the first format is easier to produce

Comments