html form to object code example

Example: form to object function

/**
 * Extracts form elements and maps to passed in object
 */
function    extractObjectFromForm($fieldContainer,objectType) {
    var innerArray=[];
    var obj = $.map($fieldContainer.find(":input"), function(n, i)
    {
        var o = {};
        if($(n).is("input:text") 
                || $(n).is("textarea") 
                || $(n).is("input:hidden") 
                || $(n).is("input:password"))
            o[n.name] = $(n).val();
        else if($(n).is("input:checkbox"))
            o[n.name] = ($(n).is(":checked") ? true:false);
        else if(n.type == 'radio') {
            if(innerArray.indexOf(n.name)==-1) {
                innerArray.push(n.name);
            }
        }
        else
            o[n.name] = $(n).val();
        return o;
    });
    $.each(innerArray,function(index,item){
        var iobj={};
        iobj[item]=$("input[name='"+item+"']:checked").val();
        obj.push(iobj);
    });
    return getObjectFromObject(obj,objectType);
}

/**
 * Takes a object created from a form scour and
 * converts it to an Object type
 */
function    getObjectFromObject(formObject,outputObject) {
    $.each(formObject,function(index,item){
        $.each(item,function(key,value){
            if(key.indexOf(".") == -1)
                outputObject[key] = value;
            else {
                var mainkey = key.substr(0,key.indexOf("."));
                var subkey = key.substr(key.indexOf(".")+1);
                outputObject[mainkey][subkey]=value;
            }
        });
    });
    return outputObject;
}