[英]How to stop 'submit' form when it is not valid and display error message?
當我輸入無效的 id 和密碼時,頁面只會顯示錯誤消息並刷新頁面。 由於我不希望頁面刷新,如何停止“提交”。
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";
}
});
嘗試使用 event.preventDefault() 方法。
https://www.w3schools.com/jsref/event_preventdefault.asp
else {
e.preventDefault();
e.stopPropagation();
document.getElementById("error").innerText = "error";
}
這也可能有幫助 - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.