简体   繁体   中英

help with javascript confirmation dialog

So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:

see updated function below ,

Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?

Edit: I figured it out , it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.

the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:

<a onclick="forceConfirm();" href="somepage.html">Blah</a>

When it should have been:

<a onclick="return forceConfirm();" href="somepage.html">Blah</a>

Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:

            function forceConfirm(){
            <?php
                if($form->errorStatus){
                    echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
                        'return true;'."\n".'}'."\n".
                        'else{ return false;}';
                }
                else{ echo 'return true;';}
            ?>
        }

Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....

You can use confirm() like this:

if(confirm("Are you sure you want to proceed?")){
    document.location = 'confirmed redirect url...';
}
else{
    document.location = 'cancel redirect url...';
}

Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM