Skip to content Skip to sidebar Skip to footer

Delete Button And Confirmation

Hi I have a working link to delete a row from my database.

Solution 1:

Solution 2:

you have to put your confirmation in the onSubmit event of the form

so if the user cancel the confirmation, the form won't be sent

<formonSubmit="return confirm('Are you sure you want to delete?')"><buttontype="submit"...></form>

Solution 3:

HTML:

<formid="delete-<?phpecho$id; ?>"action="?action=delete"method="post"><inputtype="hidden"name="id"value="<?phpecho$id; ?>" /><inputtype="submit"value="Delete this Case" /></form>

JS im assuming jquery for ease:

$("#delete-<?phpecho$id; ?>").submit(function() {
    return confirm("Are you sure you want to delete?");
});

What this does is prevent the default submit action if the js confirm returns false (doesn't submit) otherwise lets the regular post go through.

Note: you really shouldn't use html attributes to declare event handlers, this code separates the logic.

EDIT: @Nicholas comment

This is a non-jquery solution. I didn't test it, and i don't believe that preventDefault works in IE <= 8 so I probably wouldn't use it in production BUT it could be done w/o too much code jquery just makes it cross browser and easier.

functionloaded()
{
    document.getElementById("delete-<?php echo $id; ?>").addEventListener(
        "submit",
        function(event)
        {
            if(confirm("Are you sure you want to delete?"))
            {
                event.preventDefault();
            }
            
            returnfalse;
        },
        false
     );
}
window.addEventListener("load", loaded, false);

Post a Comment for "Delete Button And Confirmation"