I am using a jQuery Modal Dialog box to ask the user if they wish to submit the form or not.
However after the user clicks Dialog's Submit button, the form is not submitting.
If I then click the forms submit button again, it submits.
I am guessing this is a scope issue, I have seen some other posts about it but as yet have spent many hours with no luck. Any ideas on how to solve this?
Javascript
$(document).ready(function(){
var submitForm = $('#myform');
submit = false;
$("#confirm").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: false,
buttons: {
'Submit': function() {
$(this).dialog('close');
submit = true;
submitForm.submit();
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$("#confirm").parent().appendTo($("#myform"));
submitForm.submit(function() {
if (submit) {
return true;
} else {
$("#confirm").dialog('open');
return false;
}
});
});
HTML
<form id="myform" action="#" method="post">
<input type="text" name="check_me" />
<input type="submit" name="submit" value="Go!" />
</form>
<div id="confirm" style="display:none;">Please confirm that you want to submit</div>
Change the name attribute of your submit button from 'submit' to 'btnSubmit'
Replace the '#' in the form action attribute to blank or any other valid url.
The solution is simply... your button name. Why you ask? I shall show you!
Take this jsfiddle and notice I only made a few changes. The javascript has not changed, just the HTML
HTML
I've made two changes:
I had to do #2 because calling $('#myform').submit was referencing the button, not the submit method, and jQuery got all kinds of confused. By renaming your button, the $('#myform').submit remains the expected jQuery submit function and everybody is happy.
I stumbled upon this through going through several iterations, which I've kept below for posterity.
Good luck!
=======ORIGINAL POST BELOW========
If all you want to do is "solve this", you can refactor as follows:
HTML
JavaScript
Oddly, the below works as well:
HTML
JavaScript
The only thing I changed here was removed the submit button and 100% submit via jQuery.
You can try on submit event form have different type of events.
see this EDIT , now you can change create one function with Modal Dialog return true or false.