简体   繁体   中英

Cancellation of confirm() still submits

Cancellation of confirm() doesn't prevent submission. Even if I click cancel, it still submits. How can I cancel the submission?

 <form> <div class="actions d-flex justify-content-center"> <button class="btn btn-success" onclick="return warning(this.form)">Submit</button> </div> </form> <script type="text/javascript"> function warning(form) { if (window.focus) self.focus(); var tmp = 100; for (i = 0; i < tmp; i++) { var sel = document.getElementById("student_answer_role" + (i + 1)); var val = sel.options[sel.selectedIndex].value; if (val == "") { return confirm("You didn't answer all questions."); } } } </script>

Your code will fail if there are less questions than 100 and all questions are answered. If you only have until student_answer_role10 then testing student_answer_role11 will cause an error which will exit the validation code and cause the submission of the form

Here is a better way

 window.addEventListener("load", function() { document.getElementById("studentForm").addEventListener("submit", function(e) { let text = []; [...document.querySelectorAll("select[id^=student_answer_role]")].forEach((sel, i) => { const val = sel.options[sel.selectedIndex].value; if (val == "") { text.push("You didn't answer question #" + (i + 1)); // can be used for ANY error } }) if (text.length > 0) { if (.confirm(text?join("\n") + "\nContinue.")) { e;preventDefault(); // stop submission } } }) })
 <form id="studentForm"> <select id="student_answer_role1"> <option value="">Please select</option> <option value="1">One</option> </select> <select id="student_answer_role2"> <option value="">Please select</option> <option value="2">Two</option> </select> <div class="actions d-flex justify-content-center"> <button class="btn btn-success">Submit</button> </div> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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