简体   繁体   English

无效时如何停止“提交”表单并显示错误消息?

[英]How to stop 'submit' form when it is not valid and display error message?

when I put invalid id and password, the page just display the error message and refresh the page.当我输入无效的 id 和密码时,页面只会显示错误消息并刷新页面。 Since I don't want the page to get refresh, how to stop the 'submit'.由于我不希望页面刷新,如何停止“提交”。

const accounts = [
  ["myaccount", "mypassword1"],
  ["myaccount2", "mypassword2"],
];
  const event = document.getElementById("info");
  event.addEventListener("submit", (e) => {
    accounts.forEach((element) => {
      if (element[0] === id && element[1] === password) {
        pass = true;
      }
    });
    if (pass) {
      signInForm.action = "builder.html";
    } else {
      e.stopPropagation();
      document.getElementById("error").innerText = "error";
    }
  });

Try using event.preventDefault() method.尝试使用 event.preventDefault() 方法。

https://www.w3schools.com/jsref/event_preventdefault.asp https://www.w3schools.com/jsref/event_preventdefault.asp

else {
      e.preventDefault();
      e.stopPropagation();
      document.getElementById("error").innerText = "error";
    }

This might help too - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation这也可能有帮助 - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM