Ankit Sharma
Ankit Sharma

Reputation: 396

Javascript using Confirm to cancel form submission

How can I add a cancel button to an alert window?

I have used the confirm() method but when the submit button is clicked the confirm window pops up, but when clicking on cancel button, the form's data is stored.

I just want clicking on the cancel button to not store the data and leave the previous form as it is. This is my code:

function submitdata()
{   
    var r=confirm("Are You Sure You Want To Proceed?");

    if(r==true)
    {
        alert("Record is saved");
    }
    else
    {
        alert("Cancelling Transaction");
        javascript:history.go(0);
    }   
}

Upvotes: 3

Views: 7099

Answers (4)

John Andrea
John Andrea

Reputation: 21

Reverse the logic. But the question is weird language so its better to use a custom prompt that sets cancel to the default.

function forceNonDefaultOk() {
    return ( ! confirm( 'Keep working' ) );
}

Upvotes: 0

pkachhia
pkachhia

Reputation: 1932

Update

function submitdata() {
    var r=confirm("Are You Sure You Want To Proceed?");

    if(r==true) {
        alert("Record is saved");
        return true;
    } else {
        alert("Cancelling Transaction");
        return false;
    }   
}

Upvotes: 0

spolto
spolto

Reputation: 4551

This is all you need really:

<script type="text/javascript">

    function submitdata() { 
        return confirm("Are You Sure You Want To Proceed?"); 
    }

</script>

Upvotes: 2

user1640332
user1640332

Reputation:

<form action="" name="test" onsubmit="return submitdata();">
    <input type="text" />

    <input type="submit" />

</form>

<script type="text/javascript">

function submitdata() { 
    var r=confirm("Are You Sure You Want To Proceed?"); 
    if(r==true) { 
        alert("Record is saved"); 
    } else { 
        alert("Cancelling Transaction"); 
        javascript:history.go(0);
    }

}

</script>

Upvotes: 2

Related Questions