Mike
Mike

Reputation: 6934

jQuery - Ask user before submiting a form

I have a form with 2 submit buttons.

<input type='submit' name='submit-form' value='Send' />
<input type='submit' class='delete' name='delete' value='Delete' />

And I want to ask the user, if he really wants to delete the item. I know it could be done by making the delete button a link, but I really need to do it this way.

Thanks for your time, Mike.

Upvotes: 4

Views: 5124

Answers (2)

jAndy
jAndy

Reputation: 235962

Should look like:

$('input.delete').bind('click', function() {
    if(!confirm('are you sure') )
        return false;
});

by returning false from an event handler, it will trigger a event.preventDefault and event.stopPropagation.

In relation to your comment, I would go this way to have different strings for different inputs:

$('input').bind('click', function(e) {
    var msg;

    switch(e.className)  {
         case 'foobar': msg = 'Foo foo foo!?'; break;
         case 'yay': msg = 'yay yay yay!?'; break;
         // etc
         default: msg = 'are you sure?';
    }

    if(!confirm(msg) )
        return false;
});

Demo: http://www.jsfiddle.net/ks9Ak/

Upvotes: 6

DarkThrone
DarkThrone

Reputation: 1964

$('input.delete').click(function(e){
    e.preventDefault();
    var action = confirm('do you want to delete the item?');
    if(action){
        //delete the item the way you want
    }
});

Upvotes: 1

Related Questions