[英]How do I disable a button after 3 tries with javascript?
嘗試 3 次后如何禁用提交按鈕? 這是所有代碼(感謝DCR對 javascript 的一些幫助)
/*This Script allows people to enter by using a form that asks for a UserID and Password*/ function pasuser(form) { if (form.identifier.value=="GG") { if (form.pass.value=="123") { window.location('https://www.google.com/'); } else { alert("Invalid Password"); } } else { alert("Invalid UserID"); } }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="/style.css"> <script src="/server.js"></script> <title></title> </head> <body> <div class="box"> <h2>Login</h2> <form> <div class="inputBox"> <input type="text" name="identifier" required=""> <label>Username</label> </div> <div class="inputBox"> <input type="password" name="pass" required=""> <label>Password</label> </div> <input type="button" value="Submit" onclick="pasuser(form)"> </form> </div> </body> </html>
一種方法是添加一個計數器並在計數器達到 3 並且憑據仍然錯誤時隱藏/刪除按鈕。
但是,在服務器端執行此操作要安全得多!!!
以下是基於您的代碼的 JavaScript 客戶端解決方案,但同樣,僅在客戶端進行檢查是不安全的。
/*This Script allows people to enter by using a form that asks for a UserID and Password*/ var button = document.getElementById("submitBtn"); var attempts = 0; function pasuser(form) { attempts++; if (form.identifier.value=="GG") { if (form.pass.value=="123") { attempts = 0; window.location('https://www.google.com/'); } else { alert("Invalid Password"); button.style.display = attempts === 3 ? "none" : "block"; } } else { alert("Invalid UserID"); button.style.display = attempts === 3 ? "none" : "block"; } }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="/style.css"> <script src="/server.js"></script> <title></title> </head> <body> <div class="box"> <h2>Login</h2> <form> <div class="inputBox"> <input type="text" name="identifier" required=""> <label>Username</label> </div> <div class="inputBox"> <input type="password" name="pass" required=""> <label>Password</label> </div> <input id="submitBtn" type="button" value="Submit" onclick="pasuser(form)"> </form> </div> </body> </html>
var trieds = 0;
function pasuser(form) {
if (form.identifier.value=="GG") {
if (form.pass.value=="123") {
window.location = 'https://www.google.com/';
} else {
alert("Invalid Password");
trieds += 1;
}
} else {
alert("Invalid UserID");
trieds += 1;
}
//Change <input type='button'> for <button>
document.querySelector("button").disabled = (trieds === 3) ? true : false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.