Form inside the modal bootstrap

2019-02-09 01:31发布

问题:

I have a modal that makes the registration of products. I wanted to submit a form inside the modal without leaving the modal.

<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <form method="post">
        <button type="submit">Submit</button>
    </form>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>

回答1:

Firstly, set an id on your <form> tag:

<form id="myForm" method="post">
    ...
</form>

If you were using jQuery (highly recommended), you could do this:

$(function(){
    $('#myForm').on('submit', function(e){
      e.preventDefault();
      $.post('http://www.somewhere.com/path/to/post', 
         $('#myForm').serialize(), 
         function(data, status, xhr){
           // do something here with response;
         });
    });
});


回答2:

In my case I only put make the submit button one the footer body and remove the data-dismiss i.e:


<div class="modal-content">
    <form id="role-form"  method="get">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>

            <h4 class="modal-title">تعديل صلاحيات المدير - {{$user->username}}</h4>
        </div>
        <div class="modal-body">

            <div class="form-group col-md-12">

                <select id="role" name="role" class="form-control">
                    <option selected disabled>الصلاحية</option>
                    <option value='1'>مدير</option>
                    <option value='2'>مشرف</option>
                </select>
            </div>

            <div class="clearfix"></div>
        </div>
        <div class="modal-footer">

            <button type="submit" class="btn btn-success" >حفظ</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">إلغاء</button>

        </div>
    </form>
</div>