【问题标题】:How do you reset a form after OK is clicked in a confirm box?在确认框中单击“确定”后如何重置表单?
【发布时间】:2014-03-11 20:05:19
【问题描述】:

我有一个带有重置按钮的表单,可以清除整个表单,但我希望弹出一个确认对话框并确认用户想要重置。

我的确认框在工作,但是当按下 OK 按钮时如何让它重置表单?

下面是我目前的代码:

function reset() {
  var r = confirm("Are you sure you want to reset all text?");
  if (r == true) {
    form.reset();
  }
}
<form>
  <p>Full Name</p><br><input name="fname" type="text" placeholder="Full Name"><br>
  <p>Address</p><input name="address" type="text" placeholder="Address"><br>
  <p>Email</p><br><input name="email" type="email" placeholder="Email"><br>
  <input type="submit"> <button onclick="reset()" type="button">Reset</button>
</form>

我做错了什么?

【问题讨论】:

    标签: javascript html forms reset


    【解决方案1】:

    试试这个:

    HTML:

    <input type="reset" onclick="return confirm_reset();">
    

    JS:

    function confirm_reset() {
        return confirm("Are you sure you want to reset all text?");
    }
    

    onclick函数返回false时,它会阻止重置按钮的默认动作。

    DEMO

    【讨论】:

    • 还不如将confirm() 放在onclick 本身中,而不是创建一个新函数...只需对文本使用单引号。
    • 这是风格问题。我更喜欢保持我的 onclick 属性小。
    【解决方案2】:

    在您的表单中添加一个 id 然后就...

    document.getElementById("myForm").reset();
    

    met form reset

    Demo

    【讨论】:

    • 谢谢。我曾尝试过 getElementById,但我放的不仅仅是“.reset()”,而是“form.reset()”。
    • 不妨利用 HTML 为您提供的功能... 给 &lt;form&gt; 一个 name="myForm" 属性,然后您可以使用 document.forms.myForm.reset() 访问它。
    【解决方案3】:

    使用reset 类型的&lt;button&gt; 元素和标准方法preventDefault()

    Event 接口的preventDefault() 方法告诉用户代理,如果事件没有得到显式处理,则不应像往常一样采取其默认操作....在任何阶段调用preventDefault()事件流取消了事件,这意味着实现通常作为事件结果而采取的任何默认操作都不会发生。

    document.querySelector('form').addEventListener('reset', function(event) {
      if (!confirm('Are you sure you want to reset?')) {
        event.preventDefault();
      }
    });
    body {
      display: flex;
    }
    
    fieldset {
      margin: 0 0 16px;
    }
    
    [type="reset"] {
      float: right;
    }
    <form>
      <fieldset>
        <legend>Full Name</legend>
        <input name="name">
      </fieldset>
      <fieldset>
        <legend>Address</legend>
        <input name="address">
      </fieldset>
      <fieldset>
        <legend>Email</legend>
        <input name="email" type="email">
      </fieldset>
      <button type="submit">Submit</button>
      <button type="reset">Reset</button>
    </form>

    【讨论】:

      【解决方案4】:

      您可以为此使用 JQuery

      HTML:

      <input type="reset">
      

      JS - JQuery

      $(document).on('click', 'input[type="reset"]', function(e){
        if(confirm("Are you sure you want to reset form data?")){}
        else{
         e.preventDefault();
         window.location="#";
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-30
        • 2012-04-15
        • 1970-01-01
        相关资源
        最近更新 更多