0

I have an html template that I use with my Django website code. In the template are a couple of forms. Two of the forms are datefields and I have a confirm popup that is activated on submission if the user fills them in. I wanted the popup to exit the form submission and return to the page if the user clicks 'cancel', and to continue submitting the form if the user clicks 'ok'.

The confirm popup shows up correctly but the form submission continues no matter what the user clicks. How do I change it so that the form submission exits if the user clicks 'cancel'?

Javascript looks like this:

<script type="text/javascript">
    var checkFields = ["SPAN_START","SPAN_END"];
    function checkForm( theForm ) {

      for (i in checkFields ) {
        var fieldName = checkFields[ i ];
        var theField = theForm[ fieldName ];

        if ( theField.value ) {
          var retVal = confirm("Are you sure you want to specify a date?");
          if (retVal == true){
            theField.submit()
            return true;
          } else {
            return false;
          }
        }
      }
    }
</script>

The html where it is used looks like this:

<form action="/InterfaceApp/Nominal_Request/" method="post" class="form" onsubmit="checkForm( this )">
  {% csrf_token %}
  <div class="panel-body text-center">
    {% bootstrap_form form_span_start %}
    {% bootstrap_form form_span_end %}
    {% buttons %}
    <button type="submit" class="btn btn-primary center-block" value="Submit" name="Range">
      {% bootstrap_icon "fire" %} Generate Range of Requests
    </button>
    {% endbuttons %}
  </div>
</form>

Can anyone tell me how to cancel the submission of the form if the user clicks 'cancel'??

Much appreciated.

kdubs
  • 936
  • 3
  • 22
  • 45

1 Answers1

0

You have to return the value of the function to the inline event handler

onsubmit="return checkForm( this )"

preferably you wouldn't use inline event handlers at all, but addEventListener instead.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • `e.preventDefault();` is required too, as the former is just a convention. – Bert Peters Jul 02 '15 at 16:33
  • @BertPeters - why would `preventDefault` be required when the function returns false ? – adeneo Jul 02 '15 at 16:36
  • I could hardly phrase it better than the accepted answer to this question: https://stackoverflow.com/questions/18971284/event-preventdefault-vs-return-false-no-jquery – Bert Peters Jul 02 '15 at 16:41
  • I assumed you meant for the given answer, the inline event handler, but if using `addEventListener` you're right, then `preventDefault` would be needed instead of returning false. – adeneo Jul 02 '15 at 16:57