Dolcevita
Dolcevita

Reputation: 21

JQuery on submit show dialog

First sorry for my bad English.

I would like to show a confirmation layer (id="confirmwin") before submitting a form (id="form"). There is another button (id="yes") to submit the form.

I tried this:

Layer:

<div id="confirmwin" style="display:none">
Are you sure to submit?<br>
<a href="#" id="yes">Yes</a> <a href="#" onclick="closeconfirmwin()">No</a>
</div>

JavaScript:

$(document).ready(function(){
  $("#yes").click( function() {
    $("#form").off("submit").submit();
  });
  $("#form").on("submit", function() {
    $('#confirmwin').show();
    return false;
  });
});

Sometimes (not always) it looks like it's in an endless loop.

Perhaps the #yes click event's off event goes wrong.

Upvotes: 1

Views: 875

Answers (4)

Ricardo Vieira
Ricardo Vieira

Reputation: 740

simples as this

<form id="xpto" name="" action="" ... onsubmit="return callJavascriptFunctionConfirm();">

//bla bla bla here

</form>

function callJavascriptFunctionConfirm(){
   //do the logic here
   if (yes) 
      return true; 
   else
      return false;
}

}

Upvotes: 1

Pawel Pawlowski
Pawel Pawlowski

Reputation: 33

It is easy:

Just add an global var:

var ignoreConfirm = false;

so it will look like:

$("#yes").click( function() {
  ignoreConfirm = true;
  $("#form").off("submit").submit();
});

$("#form").on("submit", function() {
  if(!ignoreConfirm){
   $('#confirmwin').show();
   return false;
  }
});

Upvotes: 1

Robin van Baalen
Robin van Baalen

Reputation: 3651

One solution would be to pass extra parameters while triggering the submit event. You can read more about event data in the jQuery API here.

$("#yes").click( function() {
    $("#form").trigger("submit", [true]);
});

$("#form").on("submit", function(e, blnConfirmed) {
    // If it's not confirmed yet, show the overlay.
    if (!blnConfirmed) {
        $('#confirmwin').show();
        return false;
    } // else it actually IS confirmed, do a real submit
});

You should test this code first. It's just an example.

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23034

Have you tried removing the .submit() while turning it off?

$("#form").off("submit").submit();

shouldn't it be..

$("#form").off("submit")  //if

and only if confirmed proceed to do..

$("#form").submit(); //then you can /off() but I don't see the need to

Upvotes: 1

Related Questions