form to object function

Solutions on MaxInterview for form to object function by the best coders in the world

showing results for - "form to object function"
Vicente
19 Jan 2021
1/**
2 * Extracts form elements and maps to passed in object
3 */
4function    extractObjectFromForm($fieldContainer,objectType) {
5    var innerArray=[];
6    var obj = $.map($fieldContainer.find(":input"), function(n, i)
7    {
8        var o = {};
9        if($(n).is("input:text") 
10                || $(n).is("textarea") 
11                || $(n).is("input:hidden") 
12                || $(n).is("input:password"))
13            o[n.name] = $(n).val();
14        else if($(n).is("input:checkbox"))
15            o[n.name] = ($(n).is(":checked") ? true:false);
16        else if(n.type == 'radio') {
17            if(innerArray.indexOf(n.name)==-1) {
18                innerArray.push(n.name);
19            }
20        }
21        else
22            o[n.name] = $(n).val();
23        return o;
24    });
25    $.each(innerArray,function(index,item){
26        var iobj={};
27        iobj[item]=$("input[name='"+item+"']:checked").val();
28        obj.push(iobj);
29    });
30    return getObjectFromObject(obj,objectType);
31}
32
33/**
34 * Takes a object created from a form scour and
35 * converts it to an Object type
36 */
37function    getObjectFromObject(formObject,outputObject) {
38    $.each(formObject,function(index,item){
39        $.each(item,function(key,value){
40            if(key.indexOf(".") == -1)
41                outputObject[key] = value;
42            else {
43                var mainkey = key.substr(0,key.indexOf("."));
44                var subkey = key.substr(key.indexOf(".")+1);
45                outputObject[mainkey][subkey]=value;
46            }
47        });
48    });
49    return outputObject;
50}   
51