How to display a bootstrap modal on submitting a f

2019-08-29 06:16发布

问题:

I am making a form. So in that i have set javascript validation for all the fields. I want the modal to pop-up only if the form is valid when the user clicks the submit button

Pls suggest answers only using js. I not very familiar with jquery as well.Pls don't ask me to change my validation to jquery(because last time when i had asked a question about validation people told me to change it). I have tried to add onsubmit to <form> but it doesn't work

My modal

  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

My button and valiation codes

<div class="row container">
                <div class="col-sm-4"><label>Text<input class="form-control" type="text" required>
            </label>
                </div>
                <div class="col-sm-4"><label>Text<input class="form-control" type="text" required>
            </label></div>
                <div class="col-sm-4"><label>Text<input class="form-control" type="text" required>
            </label></div>
            </div>
<!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button></form>

But as you can see the modal pops up when i press the button. But i want it to pop-up onsubmit. I even tried using <form onsubmit>

回答1:

You can use on submit function:

$('form').on('submit', function (e) {
   e.preventDefault();
   $('#myModal').modal('show');
})


回答2:

JS

function myfn() {
  $('#myModal').modal('show');
}

HTML

<form onsubmit="event.preventDefault(); myfn()">
//all inputs and other info
</form>