1

I am trying to add a javascript alert to my form, the problem I am having is that when the user clicks cancel, the form still gets submitted?.

In the head I have :

<head>
<script type="text/javascript">
function confirmDelete() {if(confirm('Are you sure you want to delete this category ?'))
alert('Category Deleted !');
else alert('Cancelled !')}
</script>
</head>

My link uses the following :

a onClick="confirmDelete()"

Im not sure why clicking cancel still submits it?, is it possible to show Cancelled ! for 2 seconds and then close also ?.

Iain Simpson
  • 7,851
  • 13
  • 46
  • 64
  • 1
    This should help you: http://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms – pabrantes Nov 26 '12 at 11:15

3 Answers3

4

try using the cancel

function confirmDelete(e) {
 if(confirm('Are you sure you want to delete this category ?'))
   alert('Category Deleted !');
 else {
  alert('Cancelled !');
  e.preventDefault();
 }
}

and change your onclick to

onclick="confirmDelete(event)"
AbstractChaos
  • 4,201
  • 1
  • 17
  • 28
3

You need to return the result from the confirm:

function confirmDelete() {
    return confirm('Are you sure you want to delete this category ?');
}


onClick="confirmDelete()"
Konstantin Dinev
  • 32,797
  • 13
  • 71
  • 95
1

you can use jQuery click event and inside event put e.preventDefault(); and it will prevent default and default is submiting form-

unarity
  • 2,231
  • 2
  • 20
  • 16