views:

40

answers:

2

Does anyone know of a simple javascript library that serializes a form DOM object to JSON? I know jQuery has the serialize method but since I am writing an app for IE mobile, I can't use any of the new fancy libraries, must be oldschool simple javascript, as light as possible.

Cheers

A: 

Actually you could get all the elements in the form and "serialize" them yourself. You could get all the children of the form and process them. For example, say you have a very simple form:

<form id="my-form">
    <input type="text" name="text1" value="foo" />
</form>

var form = document.getElementById("my-form");
for(var i in form.children)
{
    if(form.children[i].type)
    {
        alert(form.children[i].name + ":" + form.children[i].value);
    }
}

There may be more advanced / efficient solutions, but this should work for simple forms.

nc3b
true, that crossed my mind, but say i have a complex table structure that arranges the layout of fields. Then I would have to filter out all tr, td, etc elements. I just thought maybe there's something out there already, also escaping necessary values, taking care of multiple selections and radio buttons with the same name...
Rok
You could always look for the value of type and maybe to a switch or something. Also, what do you mean about elements with the same name ? How will you be able to process them if they have the same name ?
nc3b
A: 

This is a very simple code, i'm writing it right now so it's better to test it before:

var form=document.getElementById("myform"); //Your form
var inp=form.getElementsByTagName("input"), 
    sel=form.getElementsByTagName("select"),
    tex=form.getElementsByTagName("textarea");
var i, parts=[];
//Select
for(i=0;i<sel.length;i++)
   if(sel[i].name) parts.push('"'+sel[i].name+'":"'+encodeURIComponent(sel[i].value)+'"');
//Textarea
for(i=0;i<text.length;i++)
   if(tex[i].name) parts.push('"'+tex[i].name+'":"'+encodeURIComponent(tex[i].value)+'"');
//Input
for(i=0;i<inp.length;i++)
{
   if(!inp[i].name) continue;
   if((inp[i].type!="checkbox" && inp[i].type!="radio") || inp[i].checked) parts.push('"'+inp[i].name+'":"'+encodeURIComponent(inp[i].value)+'"');
}

var JSONStr="{"+parts.join(",")+"}";

Anyway this does not handle some cases like multiple selects, disabled or read-only inputs etc...

mck89
He's asking to convert it to JSON, not to convert it to query string :) For this I've posted a `serialize()` function example before [here](http://stackoverflow.com/questions/2796750/confused-on-the-basics-of-ajax/2796771#2796771).
BalusC
Sorry you're right but now it should be fixed
mck89
BalusC, your solution works great, encodes correctly and supports multiple selections, thanks!
Rok