3

问题是我jQuery("form")[0].reset();在需要时用来重置表单。此方法将表单重置为初始阶段。这里初始阶段的意思是“表单第一次以某些值加载到页面中的阶段”。

但我需要将表单重置为上次保存的阶段。

我在做什么:jQuery.ajax({----});在不刷新任何页面的情况下保存表单数据。

目标是什么:通过ajax请求保存表单数据后,如果用户更改表单中的任何其他值但不想保存它并选择将表单重置为上次保存的值。如何做到这一点?因为reset();会将表单重置为初始值。

任何帮助将不胜感激。

谢谢

4

2 回答 2

1

谢谢你们的回复。

我尝试根据madalin ivascu的评论实施解决方案。还找到了一个jsfiddle来做同样的事情。通过一些修改/更改,我得到了我需要的东西。

第 1 步:编写自定义插件:

(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));

第 2 步:将序列化的表单数据保存在某处。

当您需要将表单重置为上次保存的阶段时,请使用以下命令:

yourForm.deserialize(serializedFormData);
于 2015-11-13T05:08:57.140 回答
0

让我们在你的表单结构下面说如下:

<form>
   <input type="hidden" id="recordID" value="">
   // Put your other HTML elements here
   <input type="button" id="save" value="Save">
    <input type="reset" id="reset" value="Reset">
</form>

现在,当您通过 ajax 保存表单时success,添加id您刚刚保存在#recordID字段中的记录。

现在,当您单击重置按钮时,您必须这样做:

$('#reset').click(function(e){
    e.preventDefault();
   if($('#recordID').val() != '') { // if id present then form is in edit mode
        //Do an ajax call by passing id and pull all date and populate in your form fields
   } else {
       //Form is in add mode because no id is present, just reset the form
   }
});

希望这会帮助你!

于 2015-11-12T07:22:51.907 回答