0

Here is my sample code:

<button onClick="CheckData()" type="submit">

I have some conditions in CheckData function:

if (5<6) {
   warning = "sure?";
} else if (5>3) {
   warning = "really?";
} else {
  warning = '';
}

Then I check:

if (warning.length>0) {
   return confirm(warning);
} else {
   return true; //also tried false
}

So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed.

Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form.

Any suggestions?

PS: This code is a demo and different from the real one. But the concept is the same.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84

2 Answers2

0

Change your HTML to this:

<form onsubmit="return CheckData()">
    <button type="submit" />
    ...
</form>

Explanation:

  • The onsubmit event handler is called when the form is submitted.
  • When the event handler returns false the submission is aborted.
Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
0

You can pass in the event Object to the CheckData function and prevent the default action if the confirm returns false with event.preventDefault().

<form>
<button onClick="CheckData(event)" type="submit">Submit</button>
</form>
<script>
function CheckData(e){
 var warning;
 if (5<6) {
   warning = "sure?";
} else if (5>3) {
   warning = "really?";
} else {
  warning = '';
}
if (warning.length>0) {
   var con = confirm(warning);
   if(con){
   return true;
   } else {
   e.preventDefault();
   return false;
   }
} else {
   return true; 
}
}
</script>

You can also return the result of CheckData so the default action will be prevented if it returns false.

<form>
<button onClick="return CheckData()" type="submit">Submit</button>
</form>
<script>
function CheckData(){
 var warning;
 if (5<6) {
   warning = "sure?";
} else if (5>3) {
   warning = "really?";
} else {
  warning = '';
}
if (warning.length>0) {
   var con = confirm(warning);
   return con;
} else {
   return true; 
}
}
</script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80