简体   繁体   中英

Form created dynamically from Javascript Object loop. How to save data back to object

I have the following code that takes in a string a modifies it into an object. I then create a list of items and when the user clicks on one of the list items it creates a form with the values that were in the object assigned to that key.

The problem I am having is editing the form data and saving it back to the object since the form was created dynamically.

Demo: http://jsfiddle.net/kHysL/1/

code(dont pay any attention to the code above $(document).ready()... Its the string parser) :

var str = 'View\n{\n    Name: View1;\n    Image\n    {\n        BackgroundImage: Image.gif;\n        Position: 0, 0;\n        Width: 320;\n        Height: 480;\n    }\n\n    Button\n    {\n        BackgroundImage: Button.gif;\n        Transition: View2;\n        Position: 49, 80;\n        Width: 216;\n        Height: 71;\n    }\n\n    Button\n    {\n        BackgroundImage: Button2.gif;\n        Position: 65, 217;\n        Width: 188;\n        Height: 134;\n    }\n\n    Label\n    {\n        Position: 106, 91;\n        Width: 96;\n        Height: 34;\n        Text: "Button";\n        FontSize: 32;\n        Color: 0.12549, 0.298039, 0.364706, 1;\n    }\n    Scroll\n    {\n        Position: 106, 91;\n        Width: 96;\n        Height: 34;\n        Button{\n            BackgroundImage: Button2.gif;\n            Position: 65, 217;\n            Width: 188;\n            Height: 134;\n        }\n        Button{\n            BackgroundImage: Button2.gif;\n            Position: 65, 217;\n            Width: 188;\n     \n      Height: 134;\n        }\n\n    }\n\n}';

str = str.replace(/(\w+)\s*\{/g, "$1:{"); // add in colon after each named object
str = str.replace(/\}(\s*\w)/g, "},$1"); // add comma before each new named object
str = str.replace(/;/g, ","); // swap out semicolons with commas
str = str.replace(/,(\s+\})/g, "$1"); // get rid of trailing commas
str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]"); // create number arrays
str = str.replace(/"/g, ""); // get rid of all double quotes
str = str.replace(/:\s+([^\[\d\{][^,]+)/g, ':"$1"');  // create strings

$("#parseList").html(str);

var objStr;
eval("objStr={" + str + "};");

//End Parse String

$(document).ready(function () {
    var selected;
    //Build Initial Object LIst
    var initObjectList = '<div id="main">';
    $.each(objStr.View, function (k, v) {
        initObjectList += '<div>' + k + '</div>';

    });
    initObjectList += '</div>';
    $('#main').append(initObjectList)

    $(document).on('click', '#main div div', function () {
        var index = $('#main div div').index(this);

        $(this).click(function () {
            $('#form div').remove();
            codeSnippet = "";
            x = $('#main div div').toArray();
            codeSnippet = (x[index].innerHTML);
            console.log(codeSnippet);

            var initObjectDetail = '<div id="form">';
            $.each(objStr.View[codeSnippet], function (k, v) {
                initObjectDetail += '<div>' + k + '</div>' + '<input value=' + v + '>' + '</input>';
                console.log(v);

            });
            initObjectList += '</div>';
            $('#form').append(initObjectDetail)
        });

    });
});​

Input of how to save it back to the object would be appreciated

Making the clickable object list can be greatly simplified by specifying the click handler inside the original loop that forms the list.

Form generation and Save functionality are complicated by a quirk of the data, namely that one of the objStr.View properties is a string while the other properties are objects. You will see below that we have to branch in two places to handle this difference.

$(document).ready(function () {
    var $objectList = $('<div id="main" />').appendTo($('#main'));
    $.each(objStr.View, function(k, v) {
        $('<div/>').append(k).appendTo($objectList).on('click', function(){
            var $wrapper = $('#form .wrapper').empty();
            if(typeof v === 'string') {
                $('<div class="item" />').append('<span class="key">' + k + '</span>' + '<input value="' + v + '"/>').appendTo($wrapper);
            }
            else {//object
                $('<h3 class="formHeading" />').append(k).appendTo($wrapper);
                $.each(v, function(key, val) {
                    $('<div class="item" />').append('<span class="key">' + key + '</span>' + '<input value="' + val + '"/>').appendTo($wrapper);
                });
            }
            $("<button>Save</button>").appendTo($wrapper).on('click', function() {
                if(typeof v === 'string') {
                    v = $(this).closest(".wrapper").find("input").val();
                }
                else {//object
                    $(this).closest(".wrapper").find(".item").each(function(i, div) {
                        var $div = $(div),
                            key = $div.find(".key").text(),
                            val = $div.find("input").val();
                        v[key] = val;
                    });
                }
            });
        });
    });
});

You will also see that this code doesn't need a "Save" button hard coded in the HTML. A new "Save" button is generated each time the form is populated. It doesn't have to be this way, but that's the approach I adopted.

Updated fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM