How to convert form data to object using MooTools

后端 未结 6 1825
借酒劲吻你
借酒劲吻你 2020-12-17 17:22

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

6条回答
  •  时光取名叫无心
    2020-12-17 17:49

    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.

提交回复
热议问题