jQuery: serialize elements outside forms

A good question today from Stack Overflow: how can we serialize an element which is not a form? jQuery provides the serialize() and serializeArray() methods that operate on forms by turning attributes and values into properties and values of a returned JSON object (the latter) or by building a standard query string (the former). However, creating a JSON object from an element is quite simple. Let's see why.

We have the following element:


<ul id="test">
 <li>A</li>
 <li>B</li>
 <li>C</li>
</ul>​

We can create a JSON object as follows:


$(function() {
    
    var serialized = {};
    
    $('li', '#test').each(function(i) {

           var $li = $(this);
           var $text = $li.text();
           var name = $li[0].tagName.toLowerCase();
           serialized[name + '-' + i] = $text;

    });        
    
    console.log(serialized);
});​

which will return the following output in the console:

Object
 li-0: "A"
 li-1: "B"
 li-2: "C"

Instead, if you want to store your data on the database as a JSON string, you have to follow another approach:


$(function() {
    
    var serialized = '{';
    var len = $('li', '#test').length - 1;
    var delim;
    
    $('li', '#test').each(function(i) {

           var $li = $(this);
           var $text = $li.text();
        delim = (i < len) ? ',' : '';
           var name = $li[0].tagName.toLowerCase();
        serialized += '"' + name + '-' + i + '":' + '"' + $text + '"' + delim;

    });

    serialized += '}';    
    
    console.log(serialized);
});

which outputs:

{"li-0":"A","li-1":"B","li-2":"C"}

Demo

Live demo (on jsFiddle)

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.