Tuesday, 20 August 2013

jQuery - Form submits before alertify receives confirm box value (with HTML5)

jQuery - Form submits before alertify receives confirm box value (with HTML5)

I have a form with 2 fields, one of which is required. I used HTML5
required attribute to check if the field is filled up during submission.
<form id ='reg' name='reg' action='here.php' method='post'>
<input type='text' id='name' name='name' placeholder='Name' value=''
required="true" />
<input type='text' id='contactno' name='contactno'
placeholder='Contact No' value='' />
<input type='submit' value='Register' name='register' id='register' />
</form>
Before the form actually submits, I want to show a confirm box (using
alertify jQuery plugin) to prompt the user for a submission. If a user
clicks OK, the form should submit. Otherwise, it should not. I used this
code for the confirm box checking once the submit event fires:
$("#reg").submit(function()
{
alertify.confirm("Are you sure you want to commit your reservation?",
function (e)
{
if (e) {
// user clicked "ok"
alertify.success("You've confirmed your reservation.");
return true;
} else {
// user clicked "cancel"
alertify.error("You did not confirm your reservation.");
return false;
}
});
});
Problem is, the form doesn't wait for the user's answer and submits
immediately. I tried the suggestion here, which seems ok at first. I
replaced the html button type to 'button' and replaced the jquery code to
this:
$("#register").click(function()
{
alertify.confirm("Are you sure you want to commit your reservation?",
function (e)
{
if (e) {
// user clicked "ok"
alertify.success("You've confirmed your reservation.");
$("#reg").submit();
return true;
} else {
// user clicked "cancel"
alertify.error("You did not confirm your reservation.");
return false;
}
});
});
The problem with this one is that I have a required='true' attribute for
one of the fields, which should prevent the form from submitting if the
field is empty. The code above allows submission if the user clicks OK in
the confirmation box even if the required field is still empty.
I want to check first if the field is filled up before it shows the
dialog, then wait for the user's answer and then decide whether to submit
it or not. Any suggestions on how I could get this working? Thanks in
advance! :)

No comments:

Post a Comment