Serialize all id's in a div using jquery
I am trying to create a re-ordering of the page drag and drop feature on my CMS. As some of the pages have sub pages, we have a lot of lists nested within lists. An example of the code:
$(document).ready(function(){
$(function() {
$('#contentLeft ul').sortable({
update: function() {
var order = $('#contentLeft ul').sortable('serialize');
alert(order);
}
});
});
});
<div id="contentLeft">
<ul id="sitemap">
<li id="page_1" class="page_container">
Test
<ul>
<li id="page_20">Nested one</li>
<li id="page_30开发者_如何转开发">nested 2</li>
<li id="page_40"> Nested 6</li>
</ul>
</li>
<li id="page_4" class="page_container">
Test
</li>
<li id="page_5" class="page_container">
Test
</li>
</ul>
</div>
In the above example, when I move things around and serialize the ul, i get the list of top level lists elements returned (page[]=1, page[]=4, page[]=5). What I need is for it to serialize ALL of the li tags, including the children li tags and get something like (page[]=1, page[]=20, page[]=30, page[]=40, page[]=4, page[]=5).
I have tried applying serialize quite simply to
but had no luck.
Could anyone point me in the right direcition?
Many Thanks
$(function() {
$('#contentLeft ul').sortable({
update: function() {
var order3 = [];
$('#contentLeft ul li').each(function(){
order3.push($(this).attr('id').replace(/_/g, '[]='))
});
alert(order3.join('&'));
}
});
});
try here: http://jsfiddle.net/MXCZx/1/
Alternatively you could do like this:
// serialize input elements within a specific #id
$('#id :input').serialize();
// serialize a specific element in the form
$('input[name=inputName]').serialize();
have made for my self few days ago:
function serializeUL(ul){
var children = {};
$(ul).children().each(function(){
var li = $(this),
sub = li.children('ul');
children[this.id] = sub.length > 0 ? serializeUL(sub) : null;
})
return children;
}
serializeUL('#sitemap') //will return you following JSON
{
"page_1": {
"page_20":null,
"page_30":null,
"page_40":null
},
"page_4":null,
"page_5":null
}
bit extended example of use:
http://jsfiddle.net/acrashik/E2Vte/8/
Use without form.
$(document).ready(function () {
//select html element
$('li').click(function () {
$(this).toggleClass('selected');
if ($('li.selected').length == 0)
$('.select').removeClass('selected');
else
$('.select').addClass('selected');
counter();
});
//ajax send id html element
$(document).on('click', 'li', function () {
$(this).toggleClass("check");
var form = document.querySelectorAll('li.selected'); //select the need classes
var id = {};//empty array
for (var i = 0; i < form.length; i++) {
id[i] = form[i].id; //fill the array
}
$.ajax({
url: "/site/search",
type: 'post',
dataType: "json",
data: {"selected": id},
success: function(data, response, textStatus, jqXHR) {
console.log(data);
}
});
return false;
});
});
精彩评论