Creating a simple “Delete” confirmation dialog with jQuery

I often find the need to add a confirmation to a delete link in my applications. Below is a very simple way to achieve this with jQuery.

First, you’ll need a link that you will be clicking where you want the confirmation box to pop-up.

<p><a href="/some/path/to/delete" class="delete">Delete</a></p>

Next, you will need to add in the jQuery. If you haven’t imported jQuery in you page yet, do so above this code.

<script type="text/javascript">
    $(function() {
        $('.delete').click(function() {
            var answer = confirm("Delete this item?")
            if (answer){
                return true;
            }
            else{
                return false;
            };
        });
    });
</script>

Now all this does it pops up a “confirm” dialog box and if the user clicks “OK” the link will be followed, deleting the item. If they click “Cancel” nothing will happen.

Well, that’s it. Nothing special, but comes in handy once and a while.

2 Responses

  1. Brian says:

    These lines:
    var answer = confirm(”Delete this item?”)
    if (answer){
    return true;
    }
    else{
    return false;
    };

    can be replaced by:
    return confirm(”Delete this item?”);

What do you think?

Will not be published

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


An asterix (*) indicates a required field.