【问题标题】:Clear the form once form submitted [duplicate]提交表单后清除表单[重复]
【发布时间】:2010-04-17 17:12:05
【问题描述】:

可能重复:
Resetting a multi-stage form with jQuery

提交表单后,来自另一个页面的响应会打印到#GameStorySys。但是输入到表单中的值仍然保留在那里。提交表单后,表单值是否可能消失(但表单仍应保留)?

$("[name='GameStoryForm']").click(function() { 
        $.ajax({
            type: "POST",
                data: $("#GameStoryForm").serialize(),
                url: "content/commentary/index.cs.asp?Process=EditLiveCommentaryStory&CommentaryID=<%=Request.QueryString("CommentaryID")%>", 
                success: function(output) { 
                $('#GameStorySys').html(output);
            },
                error: function(output) {
                $('#GameStorySys').html(output);
                }
        }); 
}); 

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以手动清除,例如:

    $("[name='GameStoryForm']").click(function() { 
      $.ajax({
        type: "POST",
        data: $("#GameStoryForm").serialize(),
        url: "content/commentary/index.cs.asp?Process=EditLiveCommentaryStory&CommentaryID=<%=Request.QueryString("CommentaryID")%>", 
        success: function(output) { 
          $('#GameStorySys').html(output);
          $("#GameStoryForm").get(0).reset();
          //or manually:
          // $("#GameStoryForm :input").not(':button, :submit, :reset, :hidden')
          //                           .val('').removeAttr('checked selected');
        },
        error: function(output) {
          $('#GameStorySys').html(output);
        }
      }); 
    });
    

    【讨论】:

    • 在 val 之后额外调用 removeAttr 非常好。
    • $("#GameStoryForm").get(0).reset();应该这样做。我不明白手动版本究竟是如何工作的。提交表单后,用户是否需要单击重置按钮?
    • @zurna - “手动”我只是指以编程方式清除输入,而不是使用表单的 .reset() 功能。它只是更明确一点,因此您可以确切地看到正在发生的事情......或者省略并且不清除您不想重置的任何元素。
    【解决方案2】:

    我会用 javascript 来做:

    <script>
    document.getElementById(yourFormId).onsubmit = new Function(){this.reset();}
    </script>
    

    【讨论】:

      【解决方案3】:

      如果你对AJAX查询执行reset in response函数,在请求返回之前不会进行。如果您在 onsubmit() 事件处理程序中重置表单(如此处建议),那么它根本不会被重置(因为您在 click() 处理程序中发送 AJAX 请求,而不是在 submit() 处理程序中)。

      您需要做的是在发出 AJAX 请求之后执行重置 - 即在调用 $.ajax() 之后 - 但不是在请求返回时调用的回调函数中:

      $("[name='GameStoryForm']").click(function() { 
        $.ajax({
          type: "POST",
          data: $("#GameStoryForm").serialize(),
          url: "content/commentary/index.cs.asp?Process=EditLiveCommentaryStory&CommentaryID=<%=Request.QueryString("CommentaryID")%>", 
          success: function(output) { 
            $('#GameStorySys').html(output);
          },
          error: function(output) {
            $('#GameStorySys').html(output);
          }
        });
      
        $("#GameStoryForm").get(0).reset();
      });
      

      【讨论】:

        猜你喜欢
        • 2019-03-20
        • 2019-06-07
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 2018-10-26
        相关资源
        最近更新 更多