12

I would like to convert an entire form of data to a javascript object.

<form id='myform'>
   <input type='text' name='field1' value='foo'>
   <input type='text' name='field2' value='bar'>
</form>

would convert to a javascript object...

{
   field1: 'foo',
   field2: 'bar'
}
Aldie
  • 819
  • 1
  • 11
  • 16

6 Answers6

30

In MooTools you can do easy trick how to convert all forms values into the Object:

var formObjects=$('myform').toQueryString().parseQueryString();

Convert to JSON:

var formJson=JSON.encode(formObjects);
animuson
  • 53,861
  • 28
  • 137
  • 147
Trebla
  • 316
  • 3
  • 2
4

just write your own method, basing it upon the source of the Element.toQueryString - something like this (and i know the method name is rubbish but thats the least of your worries)

Element.implement({
    toJSON: function(){
        var json = {};
        this.getElements('input, select, textarea', true).each(function(el){
            if (!el.name || el.disabled || el.type == 'submit' || el.type == 'reset' || el.type == 'file') return;
            var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
                return opt.value;
            }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
            $splat(value).each(function(val){
                if (typeof val != 'undefined') {
                    json[el.name] = val;
                }
            });
        });
        return json;
    }
});

console.log($("myform").toJSON());

tested and working fine with the example form - http://mootools.net/shell/ZSsVr/ - produces the exact result you have asked for.

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69
  • I prefer this to the accepted answer, which is a bit of a hack and would now need parts of MooTools more for `parseQueryString`. This code is very similar to `Element.toQueryString` so although means more custom code, it's not going to perform any worse. – howard10 Jan 17 '14 at 09:28
  • Worth noting that `$splat` should be replaced with `Array.from` if using a newer version of MooTools than 1.2 – howard10 Jan 17 '14 at 09:28
  • true. this was an answer from 4 yrs ago – Dimitar Christoff Jan 17 '14 at 12:39
4

I actually like a combination of Dimitar Christoff answer and Trebla:

Element.implement({
    toJSON: function(){
        var j = {};
        Array.each(this.toQueryString().split('&'),function(a){
            var kv = a.split('=')
            j[kv[0]] = kv[1]||'';
        });
        return JSON.encode(j);
    }
});
console.log($('formular_support').toJSON());
Tim Wickstrom
  • 5,476
  • 3
  • 25
  • 33
2

http://code.google.com/p/form2js/

check this out, exactly what you're need, but framework independent

Max
  • 623
  • 6
  • 8
0

MooTools doesn't come with a form serialization tool; i know, that sucks.

However, I've successfully used this stand-alone implementation: form2obj.

Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
  • 2
    oh wow. _sucks_ is a bit strong, considering writing such a tool is a matter of what, 2 min? reverting to a longer vanilla solution instead is what you _shouldn't_ do, if it can be helped. – Dimitar Christoff Jan 30 '10 at 03:44
0

One way of doing it. -- Converting it to JSON object

var hm = $('myform').toQueryString();
    hm = '{"'+hm+'"}'; 
    hm = hm.replace(/&/g, '","');
    hm = hm.replace(/=/g, '":"');
    var jsn = JSON.decode(hm); // jsn is ur JSON object.




Convert it to Hash.

Mootools has an object type called Hash. You can convert to that as well by doing the following.

Hash link : http://mootools.net/docs/core/Native/Hash It has set and get methods and you can loop and do stuff, check the link.

var hm = $('myform').toQueryString();

var ar = hm.split('&');
var finalo = new Hash();
ar.each(function(a, aCounter)
{
    var tmp = a.split('=');
    finalo.set(tmp[0], tmp[1]);
});

// finalo is your Hash object. Use the get() method to extract values. Check the link given above.
Zaje
  • 2,281
  • 5
  • 27
  • 39