Using jQuery to store the state of a complicated form

后端 未结 4 1772
天命终不由人
天命终不由人 2020-12-29 05:52

I have a rather complicated form with many \"steps\" in it that are filled in by the user. Some steps (think of them as form segments) have default options, but on clicking

4条回答
  •  旧时难觅i
    2020-12-29 06:39

    Here are a couple functions to help with this process. formToString serializes a form as a string, and stringToForm does the reverse:

    function formToString(filledForm) {
        formObject = new Object
        filledForm.find("input, select, textarea").each(function() {
            if (this.id) {
                elem = $(this);
                if (elem.attr("type") == 'checkbox' || elem.attr("type") == 'radio') {
                    formObject[this.id] = elem.attr("checked");
                } else {
                    formObject[this.id] = elem.val();
                }
            }
        });
        formString = JSON.stringify(formObject);
        return formString;
    }
    function stringToForm(formString, unfilledForm) {
        formObject = JSON.parse(formString);
        unfilledForm.find("input, select, textarea").each(function() {
            if (this.id) {
                id = this.id;
                elem = $(this); 
                if (elem.attr("type") == "checkbox" || elem.attr("type") == "radio" ) {
                    elem.attr("checked", formObject[id]);
                } else {
                    elem.val(formObject[id]);
                }
            }
        });
    }
    

    Usage:

    // Convert form to string
    var formString = formToString($("#myForm"));
    // Save string somewhere, e.g. localStorage
    // ...
    
    // Restore form from string
    stringToForm(formString, $("#myForm"));
    

提交回复
热议问题