44

I have a Bootstrap modal dialog which contains a form. The modal dialog contains a submit and a cancel button. Now on submit button click the form is submitted successfully but the modal dialog isn't getting closed. Here is my HTML:

<div class="modal fade" id="StudentModal" tabindex="-1" role="dialog" aria-labelledby="StudentModalLabel" aria-hidden="true" data-backdrop="static">
   <div class="modal-dialog">
      <div class="modal-content">
         <form action="~/GetStudent" class="form-horizontal" role="form" method="post" id="frmStudent">
            <div class="modal-footer">
               <div class="pull-right">
                  <button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-ok"></i> Save</button>
                  <button type="button" class="btn btn-danger" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
               </div>
            </div>
         </form>
      </div>
   </div>

Anybody knows how to do this?

Andreas
  • 5,393
  • 9
  • 44
  • 53
Lara
  • 2,821
  • 7
  • 39
  • 72

19 Answers19

39

Use that Code

 $('#button').submit(function(e) {
    e.preventDefault();
    // Coding
    $('#IDModal').modal('toggle'); //or  $('#IDModal').modal('hide');
    return false;
});
Muhammad Fahad
  • 1,352
  • 15
  • 15
  • 6
    This is almost correct, but do **not** return false from the event handler function as that's the same as calling `preventDefault()` and `stopPropagation()` on the event object. Calling `preventDefault()` stops the submit from happening which is not the desired outcome here. This is also why the data-dismiss attrib doesn't work - the event added by the bootstrap modal js also calls preventDefault() on the event. – othp Dec 01 '16 at 05:58
  • 10
    #button should be the id of the form, not the button (see the note at the top of [link](https://developer.mozilla.org/en-US/docs/Web/Events/submit)) - if using the event on a button, use the click event. – othp Dec 01 '16 at 06:02
  • 2
    also consider calling `.modal('hide');` rather than 'toggle', otherwise if your form can also be submitted without the modal being visible the modal will be shown when the submit event is fired. – othp Dec 01 '16 at 06:03
  • 1
    Answer is updated now in the view of your comments.. If there is something missing please share with me..Thanks – Muhammad Fahad Dec 01 '16 at 06:31
  • 1
    @othp could you edit the code in your suggested manner please? As it is now it doesn't seem to include all of your comments and I'm not exactly sure how to do it myself – Jaynes01 Feb 14 '19 at 11:51
  • Tried a lot of different ways. This was simplest and worked. –  May 31 '19 at 19:20
23

Add the same attribute as you have on the Close button:

data-dismiss="modal"

e.g.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

You can also use jQuery if you wish:

$('#frmStudent').submit(function() {

    // submission stuff

    $('#StudentModal').modal('hide');
    return false;
});
martincarlin87
  • 10,848
  • 24
  • 98
  • 145
  • 1
    which one? Are the css selectors correct? Either one of the suggestions in the answer should definitely work. – martincarlin87 Nov 02 '15 at 13:57
  • 37
    This does indeed close the modal dialog, but in my case does not trigger the inner form in the modal to be submitted. – Esteban Bouza May 09 '16 at 01:44
  • @EstebanBouza did you change the selector to match your form? The jQuery I posted would use ajax to submit the form, if you don't have it, that's why. If you don't, take out the return false but the redirect to the action of the form will probably mean it doesn't matter if the modal is closed or not since a new page will be loaded or at least the form will submit to the same page. – martincarlin87 May 09 '16 at 08:47
  • 21
    Simply adding data-dismiss on the button will not submit it. – JazzCat Aug 09 '16 at 14:02
  • 5
    Adding data-dismiss causes the modal to close before submit occurs and prevents the submit. So that does not solve the problem. The jQuery given here is the same as the accepted answer - if one reads all the comments - but this is presented easier to copy. – jgerman Jul 06 '17 at 21:34
  • @jgerman - My answer also seems to have been posted first, so if anything the accepted answer is the same as mine. – martincarlin87 Jul 07 '17 at 07:34
  • Interesting. The accepted answer was updated a couple times, so it started out wrong and was updated to be the same as your jQuery solution after you posted. – jgerman Jul 07 '17 at 19:32
  • With `data-dismiss="modal"` is not working because the request won't be send anymore. – Mr. Wizard Jul 31 '18 at 08:55
  • @Mr.Wizard remove the `data-dismiss` and try closing the modal programmatically using `$('#my-modal').modal('hide');` – martincarlin87 Jul 31 '18 at 10:02
  • 1
    If the type of button is `'button'` then you can `submit()` and then `data-dismiss`. – Mr. Wizard Aug 01 '18 at 13:44
13

give id to submit button

<button id="btnSave" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-trash"></i> Save</button>

$('#btnSave').click(function() {
   $('#StudentModal').modal('hide');
});

Also you forgot to close last div.

</div>

Hope this helps.

Rhys Jones
  • 5,348
  • 1
  • 23
  • 44
Kandarp
  • 282
  • 1
  • 10
6

You can use one of this two options:

1) Add data-dismiss to the submit button i.e.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

2) Do it in JS like

$('#frmStudent').submit(function() {
    $('#StudentModal').modal('hide');
});
kkochanski
  • 2,178
  • 23
  • 28
Mō Iđɍɨɇƶ
  • 331
  • 1
  • 8
6

If anyone does not wish to use jQuery, In Bootsrap 5.0, you should now use data-bs-dismmis e.g. :

<button type="submit" class="btn btn-success" data-bs-dismiss="modal">SUBMIT</button>

or

<button type="button" class="btn btn-success" onclick="submitForm()" data-bs-dismiss="modal">SUBMIT</button>
OriKo
  • 61
  • 1
  • 1
5

i make this code it work fine but once form submit model button not open model again say e.preventdefault is not a function..

Use below code on any event that fire on submit form

                $('.modal').removeClass('in');
                $('.modal').attr("aria-hidden","true");
                $('.modal').css("display", "none");
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');

you can make this code more short..

if any body found solution for e.preventdefault let us know

Abhi
  • 299
  • 4
  • 16
3

I am using rails and ajax too and I had the same problem. just run this code

 $('#modalName').modal('hide');

that worked for me but I am trying to also fix it without using jQuery.

Onic Team
  • 1,620
  • 5
  • 26
  • 37
Hindreen
  • 98
  • 1
  • 9
1

Neither adding data-dismiss="modal" nor using $("#modal").modal("hide") in javascript worked for me. Sure they closed the modal but the ajax request is not sent either.

Instead, I rendered the partial containing the modals again after ajax is successful (I'm using ruby on rails). I also had to remove "modal-open" class from the body tag too. This basically resets the modals. I think something similar, with a callback upon successful ajax request to remove and add back the modals should work in other framework too.

EJAg
  • 3,210
  • 2
  • 14
  • 22
1

if your modal has a cancel button (Otherwise create a hidden close button). You can simulate the click event on this button so that your form is closed. Iin your component add a ViewChild

export class HelloComponent implements OnInit {

@ViewChild('fileInput') fileInput:ElementRef;

in your close button add #fileInput

<button class="btn btn-danger" #fileInput id="delete-node" name="button" data-dismiss="modal" type="submit">Cancelar</button>

When you want to close the modal programmatically trigger an click event on the close button

this.fileInput.nativeElement.click();
  • Please don't post [duplicate answers](http://stackoverflow.com/a/43641199/6083675). If questions are duplicates, then flag to close them as duplicates. – Laurel Apr 26 '17 at 18:11
1

I had the same problem and finally got it working with this code:

<%=form_with id: :friend_email_form, url: friend_emails_create_path do |f|%>

                      # form fields entered here

<div class="actions">
    <%= f.submit "Send Email", class: 'btn btn-primary', "onclick":"submit_form();", "data-dismiss":"modal"%>
</div>

 <script>
    function submit_form() {
      document.getElementById('friend_email_form').submit();
    }
</script>

The selected answer did not work for me.

tomb
  • 1,374
  • 1
  • 13
  • 23
1

Use this to submit and close the modal at the same time

$('#form-submit').on('click', function(e){
    e.preventDefault();
    $('#con-close-modal').modal('toggle'); //or  $('#IDModal').modal('hide');
    $('#date-form').submit();
});
utkarsh2k2
  • 1,046
  • 3
  • 19
  • 42
1

I tried all things above and still had a problem: the form modal did hide but I couldn´t do any action on the html page, it seemed html window was blocked, so I finally try this solution and it worked fine.

$(document).ready(
        function() {

            // SUBMIT FORM
            $("#myForm").submit(function(event) {
                // Prevent the form from submitting via the browser.
                event.preventDefault();
                ajaxPost();

                $('#formModal').modal('hide');
                $('.modal-backdrop').remove(); // Solution
            });

            function ajaxPost() {
                // Some stuff
            }

        })
  • I had to all the way down this long thread to finally find the one-line solution that works. The Bootstrap documentation is terrible. Thank you, I spent about an hour struggling with this stupid modal. – Graham Wheeler Sep 24 '22 at 06:42
0

The listed answers won't work if the results of the AJAX form submit affects the HTML outside the scope of the modal before the modal finishes closing. In my case, the result was a grayed out (fade) screen where I could see the page update, but could not interact with any of the page elements.

My solution:

$(document).on("click", "#send-email-submit-button", function(e){
    $('#send-new-email-modal').modal('hide')
});

 $(document).on("submit", "#send-email-form", function(e){
    e.preventDefault();
    var querystring = $(this).serialize();
    $.ajax({
        type: "POST",
        url: "sendEmailMessage",
        data : querystring,
        success : function(response) {
            $('#send-new-email-modal').on('hidden.bs.modal', function () {
                $('#contacts-render-target').html(response);
            }
    });
    return false;
});

Note: My modal form was inside a parent div that was already rendered via AJAX, thus the need to anchor the event listener to document.

Devon Luongo
  • 127
  • 1
  • 2
  • 11
0

Try this code

$('#frmStudent').on('submit', function() {
  $(#StudentModal).on('hide.bs.modal', function (e) {
    e.preventDefault();
  })
});
Sagar V
  • 12,158
  • 7
  • 41
  • 68
nnattawat
  • 686
  • 5
  • 11
0

If you do not want to use jQuery, make the button type a normal button and add a click listener pointing to the function you would like to execute, and send the form in as a parameter. The button would be as follows:

<button (click)="yourSubmitFunction(yourForm)" [disabled]="!yourForm.valid" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>

Remember to remove: (ngSubmit)="yourSubmitFunction(yourForm)" from the form div if you use this method.

0

This worked for me. I embedded an inline JavaScript code in the submit button to auto-click the close button on submit. I used the ID of the close button to reference it from the javascript (jQuery).

<button type="submit" class="btn btn-success float-right" onclick="javascript: $('#close-button').click();">Save</button>
0

What I do is press the close button that automatically brings the modal to the moment the request is satisfactorily fulfilled.was what I came up with at that time and it worked for me, I am using laravel with axios

i add an ID in the close button of modal and after i select the buttton and execute when the response is correct

document.getElementById("closeGroup").click();
  • "DO NOT post images of code, data, error messages, etc. - copy or type the text into the post. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text. – cursorrux Sep 02 '21 at 17:42
0

In bootstrap 5 the modal hide function does not work as it should, so I prefer to use data-dismiss="modal" in the button.

0

Despite the question is old, I haven't found any other working solution. What I did is to handle the modal after the page was reloading. I noticed that a class modal-open was added in body tag :

<body id="page-top" class="modal-open">

and also the following div

<div class="modal-backdrop show"></div>

So, I added the following in order to remove both of them, after the page is reloaded:

$('#page-top').removeClass("modal-open"); //this was added in the 
$("div.modal-backdrop").remove();

and it worked.

yaylitzis
  • 5,354
  • 17
  • 62
  • 107