Susan Susan - 3 days ago 5
HTML Question

Javascript Block Form Submission

How would I block form submission if the user presses cancel for confirmation of selecting Doctor.

<form method="post" action="registration.php" autocomplete="off" onsubmit="return validateMyForm();">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="role" id="role">
<option value="Patient">Patient</option>
<option value="Doctor">Doctor</option>
<option value="Nurse" >Nurse</option>
</select>
<input type="submit">
</form>
<script>
$("#role").change(function(){
var val = $(this).val();

switch (val){
case "Doctor":
var d = confirm("Are you a doctor?");
}
});
</script>

Answer

To disable the submission of the form you can use return false on the onsubmit attribute of the form.

Since you already have a call to the validateMyForm() function there, you just need to make sure that this function return false:

function validateMyForm() {
    ....
    // do some checks...
    return false;
}

If you to prevent the submission of the form based on the answer to your confirm, you should save the answer in some variable that you can use later on:

<script>
    var d;
    $("#role").change(function(){
     var val = $(this).val();

      switch (val){
        case "Doctor":
          d = confirm("Are you a doctor?");
      }
    }); 
</script>

And inside the function:

function validateMyForm() {
    if (!d) {
        return false;
    }
}
Comments