Search code examples
javascriptphpformsform-submitconfirm

Returning a confirmation dialog before submitting form not working


I'm trying to get the website to return a confirmation dialog before submitting the form, but it's not working for some reason. It returned the confirmation dialog, but after clicking 'yes', it does not submit the form. What am I doing wrong?

<?php

echo "
<form action = 'delete.php' method = 'POST'>
<label id = 'delete' onclick = \"return confirm('Are you sure?');this.form.submit()\"> delete </label>
</form>
";

?>

Note:

Instead of using input:submit, I would rather use the label onclick() along with the confirmation dialog. Is that possible? Thanks.


Solution

  • The onclick handler in your code just returns confirm dialog result and ignores the rest part of code (this.form.submit()); I would recommend to use outer function in such case:

    <?php
    
    echo "
    <form action = 'delete.php' method = 'POST'>
    <label id = 'delete' onclick = \"confirmSubmit(this);\"> delete </label>
    </form>
    ";
    
    ?>
    

    js code:

    function confirmSubmit(e){
        var need_submit = confirm('Are you sure?');
        if (need_submit) e.form.submit();
    }