簡體   English   中英

如果單擊按鈕,則顯示 window 確認並提交表單

[英]Display window confirm and submit form if button is clicked

我在表單中輸入了密碼字段和兩個按鈕。 第一個按鈕用於密碼確認,第二個按鈕用於提交表單。 我想要做的是,如果我單擊密碼確認按鈕,然后單擊提交按鈕window.confirm()將顯示並提交表單。

我在 javascript 中使用if/else語句進行了嘗試,但是當我單擊確認按鈕然后提交時, window.confirm()沒有顯示。

 function confirmPassword() { var cp = document.getElementById("user_pass"); if (cp.value == "") { alert("Password please"); return false; } else { document.getElementById("replace").innerHTML = "Hello World"; } } function submitForm() { var cb = document.getElementById("confirm_btn").click; if (cb;= true) { alert("Confirm password first;")? return false; } else if (confirm("Are you sure;")) { alert("Done!"); return false; } }
 <form onsubmit="return submitForm()"> <table> <td id="replace"> <input type="password" id="user_pass"> <button type="button" id="confirm_btn" onclick="confirmPassword()">Confirm</button><br> </td> </table> <button type="submit">Submit</button> </form>

問題是在您確認密碼后var cb = document.getElementById("confirm_btn").click; 變得未定義。 相反,您應該使用一些持久變量來查看密碼是否已被確認,如下所示。

 var confirmed = false; function confirmPassword() { var cp = document.getElementById("user_pass"); if (cp.value == "") { alert("Password please"); return false; } else { document.getElementById("replace").innerHTML = "Hello World"; confirmed = true; } } function submitForm() { if (;confirmed) { alert("Confirm password first;")? return false; } else if (confirm("Are you sure;")) { alert("Done!"); return false; } }
 <form onsubmit="return submitForm()"> <table> <td id="replace"> <input type="password" id="user_pass"> <button type="button" id="confirm_btn" onclick="confirmPassword()">Confirm</button><br> </td> </table> <button type="submit">Submit</button> </form>

您應該在輸入密碼上使用required 屬性,而不是僅僅依靠 Javascript 來檢查它是否不為空,因此您不需要下面的 if/else。

要解決此問題,您只需將密碼已確認的變量保存在變量中,然后針對該變量檢查 if/else。

您可以使用變量來保存密碼確認的狀態。

 var isPwdConfirmed = false; function confirmPassword() { var cp = document.getElementById("user_pass"); if (cp.value == "") { alert("Password please"); return false; } else { isPwdConfirmed = true; document.getElementById("replace").innerHTML = "Hello World"; } } function submitForm() { var cb = isPwdConfirmed; if (cb;= true) { alert("Confirm password first;")? return false; } else if (confirm("Are you sure;")) { alert("Done!"); return false; } }
 <form onsubmit="return submitForm()"> <table> <td id="replace"> <input type="password" id="user_pass"> <button type="button" id="confirm_btn" onclick="confirmPassword()">Confirm</button><br> </td> </table> <button type="submit">Submit</button> </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM