Sam
Sam

Reputation: 5250

Why is my Bootstrap modal's hide code not working properly?

My Bootstrap modal hide code is not working. The "else" alert appears, showing that I'm in the else statement, but my modal is not hidden as it should be after that. Why isn't the modal hiding properly?

$("#buy").click(function () {
   $("#buy").click(function () {
   var a = 4;
   if (a == 5) {
     alert("if");
     $('#myModal').modal('show');
   }
   else {
    alert("else");
    $('#myModal').modal('hide');
   }
 });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>


<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>

<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
  <div class="modal-bootstrap-dialog modal-sm">
    <div class="modal-bootstrap-content">
      <div class="modal-bootstrap-body">
        -- content ----
      </div>
    </div>
  </div>
  <div class="modal-bootstrap-footer">
     <button type="submit" class="button primary" data-dismiss="modal">Close</button>
     <button type="submit" class="button primary">Save changes</button>
  </div>
</div>

Archive.org-based Bootply (Codeply) Demo

Upvotes: 57

Views: 169347

Answers (25)

albertedevigo
albertedevigo

Reputation: 18411

You are using both modal toggling methods: via JavaScript and via data attributes. So your click is firing the modal show as your data attributes set, and your JavaScript does not affect this trigger.

Just remove the data attributes and go with the JavaScript method:

<button class="button primary" id="buy" style="text-decoration:none;" type="button">Review and confirm</button>

<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
    <!-- modal contents -->
</div>

<script type="text/javascript">
$("#buy").click(function () {
    var a = 4;
    if (a == 5) {
        alert("if");
        $('#myModal').modal('show');
    } else {
        alert("else");
        $('#myModal').modal('hide');
    }
});
</script>

Upvotes: 51

quinlan
quinlan

Reputation: 122

Before you open a loading modal, make sure that you close all others. This is the function is use to close the modal:

function hideLoadingModal() {
    $('#loadingModal').on('shown.bs.modal', function () {
        $('#loadingModal').modal('hide');      
    }); 
}

Now if I want to open the modal I call the above function and open a new one after that. Like this:

hideLoadingModal();
$('#loadingModal').modal('show');

Upvotes: 0

Vaios P.
Vaios P.

Reputation: 404

This is an improvement on Tang Chanrith's answer, which worked for me. This version removes the padding-right and re-adds the scrollbar.

You just have to delete a class from body and the CSS that is generated:

function hideModal() {
    $("#myModal").removeClass("in");
    $(".modal-backdrop").remove();
    $('body').removeClass('modal-open');
    $('body').css('padding-right', '');
    $("#myModal").hide();
}

Upvotes: 20

ninjaneer
ninjaneer

Reputation: 7031

If you're using fade, you'll have to use JavaScript to remove fade class.

Upvotes: 21

Giuliano Ara&#250;jo
Giuliano Ara&#250;jo

Reputation: 126

I had the same problem but I didn't want to remove the fade class. A simple solution I found was to use a setTimeout of 100ms.

setTimeout(function () { $("#myModal").modal('hide') }, 100);

Upvotes: 0

Budi Odank
Budi Odank

Reputation: 11

  1. Remove fade class.

  2. Create function to close modal

    function stopLoading() {
       $("#loadingModal").modal("hide");
    }
  3. Add set timeout when close modal (1000 = 1s)

    setTimeout(stopLoading, 1000)

It's working for bootstrap 4 and Admin LTE 3

Upvotes: 1

Stefan Drazic
Stefan Drazic

Reputation: 11

For those still struggling, you need to call .hide() on the same instance of the element.

Upvotes: 0

Joseph Ali
Joseph Ali

Reputation: 355

let btnSaveChanges = document.getElementById("btnSaveChanges")

btnSaveChanges.onclick = function () {
    hideModal()
}

function hideModal() {
    // Get the modal element
    var modalElement = document.getElementById('updateModal');

    // Create a Bootstrap modal instance
    var modal = bootstrap.Modal.getInstance(modalElement);

    // Hide the modal
    modal.hide();
}

Upvotes: 1

Daphoque
Daphoque

Reputation: 4678

Same issue here for no reason, i'm not using "fade" stuff. I open modal and close modal only with js, the hide function is working only when called inside a setTimeout.

<script>
var modal_show = function(){
    $("#modal_post").modal("show");
};

var modal_hide = function(){
    $("#modal_post").modal("hide");
};

window.addEventListener("message", function(event){ 
   // listening iframe post message
   modal_hide();
});
</script>

<div class="modal" id="modal_post" tabindex="-1" role="dialog" style="width: 100%;" data-keyboard="false" data-backdrop="static">
  <div class="modal-dialog" style="width: 450px; height:600px; background: white; border: none; box-shadow: none;" role="document">
    <div class="modal-content"  style="width: 100%; background: white; border: none; box-shadow: none;">
      
      <div class="modal-body" style="width: 100%; background: white; border: none; box-shadow: none; padding: 0;">
        <div>
            <iframe src="https://perdu.com" style="width:450px;height:600px;"></iframe>
        </div>
      </div>
      
    </div>
  </div>
</div>

For no reason, modal_hide(); is working inside the console but not in my code.

If i replace the modal_hide(); in the event listener with setTimeout(modal_hide, 200); it's working properly

Upvotes: 0

Roman86
Roman86

Reputation: 2309

if nothing helps (that happens) - make sure that nobody prevents it like below (my case):

$modal.on('hide.bs.modal', function (e) {
  if (shouldNotBeClosed) {
    return e.preventDefault();
  }
});

Upvotes: 0

Vitold
Vitold

Reputation: 39

    G.modals = [];
    /**
     * 
     * @param {
     *  modalId: string,
     *  callback: function
     * } options 
     * @returns 
     */
    const openModal = (options) => {
      const {
        modalId = false,
        callback = () => { }
      } = options;
      if (!modalId) return;
    
      const modalNode = document.querySelector(`#${modalId}`);
      modal = new bootstrap.Modal(modalNode);
      modal.show();
    
      const modalObject = {
        modal,
        id: modalId
      };
    
      G.modals.push(modalObject);
    
      callback();
    };
    
    /**
     * 
     * @param {
     *  modalId: string,
     *  callback: function
     * } options 
     * @returns 
     */
    const closeModal = (options) => {
      const {
        modalId = false,
        callback = () => { }
      } = options;
      if (!modalId) return;
    
      const currentModal = G.modals.find(item => item.id === modalId)  || false;
      if(!currentModal) return;
      const { modal } = currentModal;
      const { _element, _backdrop } = modal;
    
      _element.classList.remove('show');
      _backdrop._element.remove();
      G.modals.splice(G.modals.indexOf(currentModal), 1);
    
      callback();
    };
    
    
          openModal({
            modalId: 'your-modal-id',
            callback: () => {
              DoSomethingAfterModalOpened();
            }
          });
    
          closeModal({
            modalId: 'your-modal-id',
            callback: () => {
              DoSomethingAfterModalClosed();
            }
          });

Upvotes: -1

Merrin K
Merrin K

Reputation: 1790

Try this

give an id to close button

<button type="submit" id="modalcloseBtn" class="button primary" data-dismiss="modal" >Close</button>

and trigger onclick event

$('#modalcloseBtn').trigger("click");

Upvotes: 0

Oleg Vitols
Oleg Vitols

Reputation: 71

None of the above solutions worked for me. If this is your case, try to imitate click event on the close button (the one which is added dynamically):

<div class="modal" tabindex="-1" role="dialog" id="modal" area-hidden="true" style="display: inline-block;">
        <div class="modal-dialog modal-dialog-centered" role="document">
            ...
        </div>
    <a href="#close-modal" rel="modal:close" class="close-modal ">Close</a></div>
</div>

$('.close-modal').click() should resolve the issue.

Upvotes: 0

Bharathiraja
Bharathiraja

Reputation: 812

Hide modal dialog box using bootstrap

Method 1: using bootstrap

$('.close').click(); 
$("#MyModal .close").click();
$('#myModalAlert').modal('hide');

Method 2: using stop-propagation

$("a.close").on("click", function(e){
  $("#modal").modal("hide");
  e.stopPropagation();
});

Method 3: After shown method invoke

$('#myModal').on('shown', function () {
      $('#myModal').modal('hide');
})

Method 4: Using CSS

this.display='block'; //Set block css
this.display='none'; //set none css after close dialog

Upvotes: 1

sksankar
sksankar

Reputation: 50

One possible reson should be the order of jquery and bootstrap and your script is not in proper sequence. Below should be the sequence.

1. <script src='js/jquery-3.2.1.min.js'></script>
2. <script src='js/bootstrap.min.js'></script>
3. your own script:
<script type="text/javascript">
$("#buy").click(function () {
   var a = 4;
   if (a == 5) {
     alert("if");
     $('#myModal').modal('show');
   }
   else {
    alert("else");
    $('#myModal').modal('hide');
   }

});
</script>

Upvotes: 0

Gowtham Ag
Gowtham Ag

Reputation: 187

I am also having the same problem, where I can't find the correct solution for it.

Later I observed that what is happening when the modal gets closed when it works well.

Three Main properties are,

  • modal-open class gets removed from <body> tag.
  • In <body> tag change CSS .
  • <div> class of modal-backdrop gets removed.

So, When u do these things manually, you will achieve it, when not works.

The code should be as following in Jquery,

      $('body').removeClass('modal-open');        
      $('body').css('padding-right', '');
      $(".modal-backdrop").remove();
      $('#myModal').hide();

Hence, try this and get a solution.

Upvotes: 0

Naveed Alam
Naveed Alam

Reputation: 11

I was opening the modal popup when I click on the link using data-toggle="modal" attribute which was bound with that link and trying to close it using javascript but I was failed each time, so when I remove the "data-toggle" attribute and "href" from that link and opened it using javascript then it was closing properly using javascript as well.

from the below few lines of code, you can understand easily

<a href="#CustomerAdvancedModal" data-toggle="modal" class="classShowAdvancedSearch">Advanced Search</a>

I changed the above link to something link this

 <a href="#" class="ebiz-Advanced-Search classShowAdvancedSearch">Advanced Search</a>

After that when I try to close it using javascript, then I become successful

$("#CustomerAdvancedModal").modal('hide');

Upvotes: 0

Brenden Stefano
Brenden Stefano

Reputation: 1

I had the same issue. I tried the JavaScript way suggested in the post, unfortunately it only worked half of the time. If I triggered my modal a few times, it bugs out. As a result I created a work around using CSS:

/* Hide the back drop*/
.modal-backdrop.show {
    display: none;
}
/* Simulate the backdrop using background color */
.modal-open .modal {
    background-color: rgba(47, 117, 19, 0.3);
}

Upvotes: 0

Mathieu
Mathieu

Reputation: 11

I had the same problem, my mistake was that I was trying to open the modal window a few times. We must test that the modal window is not already open before trying to open it.

    if (!($("#MyModal").data('bs.modal') || {})._isShown){ 
        $("#MyModal").modal('show');
    }

Upvotes: 1

Takechi Ponchai
Takechi Ponchai

Reputation: 31

I have solution this problem.

$('#landingpage, body').on('click',function(){
    $( ".action-close" ).trigger( "click" );});

Upvotes: 3

Feuda
Feuda

Reputation: 2365

You should try this $('.modal.in').modal('hide')

Via https://github.com/twbs/bootstrap/issues/489

Upvotes: 1

Prathap Kudupu
Prathap Kudupu

Reputation: 1353

In the java script code you need to add one line of code

$("#savechanges").on("click", function (e) {
        $("#userModal").modal("hide");
        e.stopPropagation(); //This line would take care of it
    });

Upvotes: 1

Tang Chanrith
Tang Chanrith

Reputation: 1449

Try this function

function hideModal(){
    $("#myModal").removeClass("in");
    $(".modal-backdrop").remove();
    $("#myModal").hide();
}

Upvotes: 17

iMichaeln
iMichaeln

Reputation: 46

try to add return false like this:

$("#buy").click(function () { 
  var a = 4;
  if (a == 5) {
    alert("if");
    $('#myModal').modal('show');
  }
  else {
    alert("else");
    $('#myModal').modal('hide');
  }
  return false;
});

Upvotes: 2

Kshitiz
Kshitiz

Reputation: 2743

I checked your code. Now you compare a == 5. but a is always 4. you may have to check this why you are doing this comparison. Also you need you remove the data-target if you want to open modal from javascript :

<button class="button primary" id="buy" data-toggle="modal" style="text-decoration:none;" type="button">Review and confirm</button>

data-target directly opening the modal. Check if this is working.

Upvotes: 1

Related Questions