17

I am trying add a confirmation before a form is submitted using jQuery. I found a nice example in another Stack Overflow question form confirm before submit but I can't get it to work.

jQuery:

$(function() {
    $('form#delete').submit(function() {
        var c = confirm("Click OK to continue?");
        return c;
    });
});

Template:

<form id="delete" action="{% url 'item_delete' item.id %}" method="post">{% csrf_token %}
    <input class="floatright" type="submit" value="Delete" />
</form>

How can we achieve this?

Community
  • 1
  • 1
Hans de Jong
  • 1,870
  • 6
  • 33
  • 53

5 Answers5

27
   $('#delete').submit(function(event){
     if(!confirm("some text")){
        event.preventDefault();
      }
    });
iHadaj
  • 435
  • 4
  • 6
21

You are submitting the form and after are checking for confirm, you need to the inverse

JS:

$(function() {
   $("#delete_button").click(function(){
      if (confirm("Click OK to continue?")){
         $('form#delete').submit();
      }
   });
});

HTML:

<form id="delete" action="{% url 'item_delete' item.id %}" method="post">{% csrf_token %}
    <input id="delete_button" class="floatright" type="button" value="Delete" />
</form>
brunozrk
  • 703
  • 6
  • 14
  • 1
    I added `event.preventDefault();` in an 'else' condition – campeterson May 15 '14 at 15:39
  • 2
    This will **not** work if you submit the form in any way besides clicking this button (e.g., pressing enter in another input). @user3311206's answer is better because of this. – Ben Mar 26 '17 at 20:08
  • 1
    To follow up on Ben's comment, the user3311206 he is referencing is iHadaj's answer from April 4, 2010 - https://stackoverflow.com/a/22989986/160830 – Scott Mitchell Sep 24 '18 at 22:05
1

Use following line of code on your submit button

onclick="if (confirm('some text')) return true; else return false;"

Example

<form id="delete" action="{% url 'item_delete' item.id %}" method="post">{% csrf_token %}
<input class="floatright" type="submit"  onclick="if (confirm('some text')) return true; else return false;" value="Delete" />
sharif779
  • 124
  • 2
  • 9
0

Make sure that you put your code in $(document).ready(), like this:

$(document).ready(function () {
    $('form#delete').submit(function() {
        var c = confirm("Click OK to continue?");
        return c;
    });
}); 
Zvonimir Burić
  • 498
  • 3
  • 11
0
    $(function() {
       $('form#delete').click(function(e) {
        e.preventDefault();
        var c = confirm("Click OK to continue?");
        if(c){
            $('form#delete').submit();
          }
      });
  });

    <form id="delete" action="www.google.com">
        <input id="deletesubmit" type="submit" value="Delete" />
    </form>
Tuhin
  • 3,170
  • 1
  • 13
  • 25