How to prevent bootstrap modal from closing from button using onclick?

If you catch the click-event from the button like this:

     $('#buttonId').off('click').click(function(clickEvent){
        //enter code here
     });

you actually can prevent the closing of your modal. For this, depending on your situation, you will find these two functions useful:

     clickEvent.preventDefault();
     clickEvent.stopPropagation();

If I understood this site (which is in German) http://www.mediaevent.de/javascript/event-handler-default-verhindern.html correctly, preventDefault() stops the immediate default action (such as following a link). However, the event itself will still travel through the DOM and can be "heard" by various event listeners, one of these is the event listener that hides the modal. For this the second function is needed, which stops the event's travel through the DOM. Thus, it can't be heard by the hiding listener and the window won't be closed (hidden). Therefore, I suggest to implement the functions like so:

     $('#buttonId').off('click').click(function(clickEvent){
        //enter code here
      var myDataIsValid = true;
      // check if Data is valid => myDataIsValid = true or false
      if(myDataIsValid){
       //do Stuff
      }else{
       clickEvent.preventDefault();
       clickEvent.stopPropagation();
       //do other Stuff
      }
    });

In my code, I only need to use stopPropagation(), as my default action is wanted, so you can use the two functions independently.

note: This solution only was tested with a Firefox browser


Since you are using jQuery anyway, try not to have JavaScript/jQuery embedded in your code.

$('#buttonId').on( 'click', function () {
   // either call do_save or embed the contents of do_save in here
   var myDataIsValid = true; // change to call validator function
   if (myDataIsValid) {
     $('#myModal').modal('hide');
   }
   return true; // value depends on whether you want stopPropagation or not.
});

HTML:

<button id="buttonId" type="button" class="btn btn-success btn-sm">Save</button>

As an alternative, you can probably prevent closing by intercepting the 'hide' event and returning false from that.


Don't use the data-dismiss="modal" and let your function close (hide) your modal:

<button type="button" class="btn btn-success btn-sm" onclick="do_save()">Save</button>

"

function do_save()
    {
        if(Math.floor(Math.random() * 2)==1)
        {
            console.log('success');
            $('#myModal').modal('hide');
            return;
        }   
        console.log('failure');
        return false;
    }