简体   繁体   中英

Page redirect on clicking of “Cancel” button of a confirm dialogue

Please look at the code snippet -

<form action="post" onsubmit="return confirm('Are You Sure?')">
       <a id="saveBtn" class="btnClass">Save<a/>
</form>

When I click on the 'Save' and then Click on the " Ok " button of confirm popup the form get submitted. If I click " Cancel " the form is not submitted and the I left on the current page. Is it possible if I click " Cancel " button then the page redirected to other page?

You should probably not use the onsubmit attribute, go with the unobtrusive event listener approach for better readability and maintainability.

Something like this should show the general idea and you can update it with your own redirect link:

var submitLink = document.getElementById('saveBtn'),
    myForm = document.getElementById('myForm');

submitLink.addEventListener('click', function(e) {
    if (confirm('Are You Sure?')) {
        myForm.submit();
    } else {
        e.preventDefault();
        window.location = 'http://google.com'; // redirect to your own URL here
    }
});

This relies on the form and anchor having id attributes:

<form action="post" id="myForm">
   <a href="#" id="saveBtn" class="btnClass">Save<a/>
</form>

Yes you can because the confirm will return true/false you can code additional behavior for false result, an example is:

<form action="post" onsubmit="return confirm('Are You Sure?')? true:window.location.assign('http://www.w3schools.com')">
   <a id="saveBtn" class="btnClass">Save<a/>

You can handle the confirm dialog by equating the state to true or false.

function myFunction() {
 var r = confirm('Are You Sure?');
 if(r==true) 
 return true;
 else {
    event.preventDefault();
    window.location="http://example.com";
 }
}

Here is a working fiddle https://jsfiddle.net/BoyWithSilverWings/p7knLr3m/

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