Assign JavaScript function to submit button, which should execute conditionally

fvgs picture fvgs · Aug 22, 2012 · Viewed 7.3k times · Source

I have a simple form with one hidden input field, and a submit button. When the user clicks the submit button, I want it first to run a JavaScript function with a confirm() function. Depending on whether the user hits 'Ok' or 'Cancel', I want the form to submit, or to not submit. How do I successfully assign an on-click function to a submit button, and have it work as described above?

function confirmDelete() {
var del = confirm("Are you sure you wish to delete this post?");

if (del)
  //continue and submit the form
else
  //the form should not be submitted
}

Here is the form:

<form action="/delete/" method="post">
<input type="hidden" name="path" value="'.$path.'" />
</form>

I realize that I could scrap the form altogether and just pass the hidden variable as a GET variable to the /delete/ page, however I would prefer to use a POST variable for security reasons.

Answer

Niet the Dark Absol picture Niet the Dark Absol · Aug 22, 2012

This would suffice:

<input type="submit" value="Delete" onClick="return confirm('Are you sure?');" />