jqueryajaxformsjqueryform

How to reset form to last saved(through ajax) stage


The thing is I'm using jQuery("form")[0].reset(); to reset a form whenever required. This method is resetting form to its initial stage. Here initial stage means, "the stage when form was loaded into the page for first time with some values".

But what I need is to reset the form to last saved stage.

What I'm doing: Saving form data through jQuery.ajax({----}); without any page refresh.

What is target: After saving form data with an ajax request, if user change any other values in form but don't want to save it and opt to reset form to last saved value. How to achieve that? Because reset(); will reset form to initial values.

Any help will be highly appreciated.

Thank you


Solution

  • Thanks for your responses guys.

    I tried to implement a solution based on madalin ivascu's comment. Also found a jsfiddle to do the same. With some modifications/changes I got what I needed.

    Step 1: Write a custom plugin:

    (function($) {
        $.fn.deserialize = function (serializedString) {
            var form = jQuery(this);
            form[0].reset();
            serializedString = serializedString.replace(/\+/g, "%20");
            var formFieldArray = serializedString.split("&");
            jQuery.each(formFieldArray, function(i, pair) {
                var nameValue = pair.split("=");
                var name = decodeURIComponent(nameValue[0]);
                var value = decodeURIComponent(nameValue[1]);
    
                var field = form.find("[name='" + name + "']");
                if (field[0] != undefined) {
                    if (field[0].type == "radio" || field[0].type == "checkbox") {
                        var fieldWithValue = field.filter('[value="' + value + '"]');
                        var isFound = (fieldWithValue.length > 0);
                        if (!isFound && value == "on") {
                            field.first().prop("checked", true);
                        } else {
                            fieldWithValue.prop("checked", isFound);
                        } 
                    } else {
                        field.val(value);
                    }
                }
            });
        }
    }(jQuery));
    

    Step 2: Save serialized form data somewhere.

    When you need to reset form to last saved stage, use this:

    yourForm.deserialize(serializedFormData);