【问题标题】:Multiple onClick submit() buttons and multiple forms misbehave多个 onClick submit() 按钮和多个表单行为不端
【发布时间】:2021-07-28 11:38:02
【问题描述】:

我有两个带有两个单独的 onclick submit() 按钮的表单。问题是,无论 ID 是什么,只有第一个表单被发送出去。我尝试使用 getElementByClassName 和 Tagname 以及为表单提供不同的名称,但仍然无法正常工作..

<script>
        function submitForm() {
                   document.getElementById("formDelay").submit()
               }
               document.getElementById('formDelayButton').onclick = function() {
                   setTimeout(submitForm, 900);
               };
         
        function submitForm1() {
                document.getElementById("formDelay1").submit()
                  }
            document.getElementById('formDelayButton1').onclick = function() {
                      setTimeout(submitForm, 900);
                  }; 
</script>


<% if(userSecrets.length != 0){ %>
    <p>My shared secrets</p>
    <form action="/mysecrets/delete" method="POST" id="formDelay1">
      <div class="form-group">
        <select class="form" name=" secret">
          <% userSecrets.forEach(function(secret){ %>
          <option value="<%= secret %>"><%= secret %></option>
          <% }); %>
        </select>
    </form>
    <button type="submit" class="button" id="formDelayButton1">Delete Secret</button>
    <%  } %>

    <% if(userSecrets.length == [] ){ %>
    <p>You haven`t shared any of your secrets yet. <br> This is the perfect time to do so!</p>
    <%  } %>

    <form action="/mysecrets" method="POST" id="formDelay">
      <div class="form-group">
        <input type="text" class="form" name="secret" placeholder="What's your secret?">
      </div>
    </form>

    <button type="submit" id="formDelayButton" class="button">share it
    </button>

【问题讨论】:

  • 你有两个函数 submitFormsubmitForm1 但你总是使用 submitForm

标签: javascript html forms ejs


【解决方案1】:

你有两个函数 submitFormsubmitForm1 但你总是使用 submitForm

无论如何你都可以做得更好:

document.querySelectorAll('form').forEach(form => {
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    setTimeout(() => {
      form.submit();
    }, 3000);
  });
});
<p>Form 1</p>
<form>
  <button type='submit'>Submit form 1</button>
</form>
<p>Form 2</p>
<form>
  <button type='submit'>Submit form 2</button>
</form>

【讨论】:

  • Ill have a look later on I hope it works! I appreciate your response.? I know I had that typo, but regardless changing it, will carry out the same misbehaviour. I think maybe the reason is that the buttons are outside of the forms. But even they outside I dont 知道它是如何发送错误的表格的深入。再次感谢您!
  • 原因是按钮在表单之外才是真正的问题
  • 是的,我移动了表单中的按钮,它确实有效。现在我把它改成了你的代码,它也可以工作。 :) 显然你的解决方案比我的解决方案优雅得多。我只是将它移到表格之外,因为我在这里指的是 Rus Mine 评论:stackoverflow.com/questions/4148210/…。非常感谢您的时间和精力!欣赏!
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多