0

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jaehyuck Choi
  • 169
  • 11
  • I made you a snippet. Please add relevant HTML line the select you are testing – mplungjan May 07 '20 at 11:43
  • Does this answer your question? [JavaScript Form Submit - Confirm or Cancel Submission Dialog Box](https://stackoverflow.com/questions/6515502/javascript-form-submit-confirm-or-cancel-submission-dialog-box) – Alon Eitan May 07 '20 at 11:44
  • 1
    Doing this in a loop this way does not make much sense to begin with. You would get the prompt on the _first_ question that does not have an answer, and the user’s reaction to that first prompt would then determine whether the form would get submitted or not. – CBroe May 07 '20 at 11:44
  • Where are you performing the cancel action, i can just see one submit button. – raj240 May 07 '20 at 11:47

1 Answers1

0

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236