Razib Razib - 1 month ago 19
jQuery Question

Redirect on deny of a confirm dialog

My task is to submit a from based on user confirmation. If the user confirm then the form is submitted. If the user deny then the from is redirected to other page. I've a form in jsp like this -

.....
<form id="stageUpdateForm" method="post">
</form>
......


And in javascript I'm trying -

$('#stageUpdateForm').submit(function() {
decision = confirm("Some data changed. Are you sure?");
return decision;
// if user deny then redirect
});


Now if the user deny to submit the from its stay in current page. But I want to redirect the page to other url (eg. - www.google.com) if the user deny. How can I do this?

Answer

You can do:

$('#stageUpdateForm').submit(function () {
    var decision = confirm('Some data changed. Are you sure?');

    // if user deny then redirect 
    if (!decision) {
        $(location).attr('href', 'http://www.google.com');
    }

    // If user confirm, than it will return true and the form will be sumbited
    return decision;
});