简体   繁体   中英

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);
    }   
}
<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>

This is all you need really:

<script type="text/javascript">

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

</script>

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;
    }   
}

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' ) );
}

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