Cheknov
Cheknov

Reputation: 2072

How to trigger form submit from JavaScript after jQuery modal popup

Let's say I have the following form:

<form id="evidence-formset" action="{% url 'interpret-criteria' %}" method="post">
  <div class="form-group row">
    <!-- Some content here -->
    <div class="col-auto">
      <input type="submit" class="btn btn-primary" value="Calculate" />
      <input type="reset" class="btn btn-secondary" value="Reset" />
      <input type="submit" class="btn btn-dark" value="Register" onclick="validateRegister()" formaction='https://www.wikipedia.org/'/>
      <input type="submit" class="btn btn-link" value="Export results as Excel" formaction="{% url 'export-interpretation' %}" />
    </div>
  </div>
<form>

And the following JS function (WIP):

function validateRegister() {
  event.preventDefault();
  $("#myModal").modal();
  $("#registerSubmit").submit()
}

And this basic modal:

<div class="modal" id="myModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Register changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

So basically what I want is that when I click the Register button a modal shows, asking for confirmation. If I click again on 'Register' then the input will submit and the webpage should redirect to wikipedia (this is just an example). If I click Close, no form should be submitted and the modal will disappear.

I checked all the previous StackOverflow questions and I couldn't find an answer that worked for me. The closest solution I found is this but it doesn't work.

UPDATE WITH A SOLUTION:

function validateRegister() {
  event.preventDefault();
  $("#myModal").modal();
  $("#myModal").on("click",".btn-primary", function(){
    $('#evidence-formset').attr('action', 'https://www.wikipedia.org/').submit();
  });
}

Upvotes: 0

Views: 105

Answers (1)

mplungjan
mplungjan

Reputation: 177692

  1. remove onclick and add this

$("#evidence-formset").on("submit",function(e) {
  e.preventDefault();
  $("#myModal").modal();
})
  1. Add ok/cancel to the buttons of the modal

$("#myModal").on("click",".btn-primary", function(){
   $("#evidence-formset").submit(); // you can add if (validate(....) in front if you have any validation
});

$("#myModal").on("click",".btn-secondary", function(){
  $("#myModal").modal('toggle');
});

Upvotes: 1

Related Questions