【问题标题】:How to link two buttons in html如何在html中链接两个按钮
【发布时间】:2022-01-14 06:13:50
【问题描述】:

我有一个包含两个部分的 HTML 文件。一个部分里面有一个表格。另一个有消息。 如果用户提交表单,则会显示一条消息,并且用户必须按下另一个按钮才能完成提交。

有没有办法链接一个按钮,让用户必须按下另一个按钮才能完成原始按钮工作?

<section>
  <form>
    <input>...
    <button> 
        // User presses the first submit button
      </button>
  </form>
</section>
<div>
  <button>
     // User has to press this button next inorder to complete the form
   </button>
  <div>

【问题讨论】:

  • 仅供参考,HTML 中的 cmets 以 &lt;!-- 开头并以 --&gt; 结尾,所以 &lt;!--your comment here--&gt;

标签: javascript html button


【解决方案1】:
const form = document.querySelector("form"); // First grab the form
const btn2 = document.getElementById("button2"); // Second button, make sure to add the id or any other proper selector

let isSubmitted = false;

// Once form will be submitted from inside
// we will prevent the default behaviour of it so it does not do anything other than
// marking isSubmitted as true, so this can be checked in other actions
form.addEventListener("submit", (e) => {
  e.preventDefault();
  isSubmitted = true;
});

// Once the form is submitted once, only then 
// trigger programmatically the actual behaviour
btn2.addEventListener("click", () => {
  if (isSubmitted) {
    form.submit();
  }
});

这样,您还可以使用isSubmitted 变量,并将其再次标记为 false,每当有人执行需要表单本身额外确认的操作时。

【讨论】:

  • @K.KDesgins 我已经更新了我的答案,正确解释了每一行以及代码背后的逻辑
  • 更新了@cloned
猜你喜欢
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 2017-07-29
  • 2016-01-26
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多