TAGS :Viewed: 8 - Published at: a few seconds ago

[ Page redirect on clicking of "Cancel" button of a confirm dialouge ]

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?

Answer 1


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>