Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i have modal with button (Save)

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

how to prevent closing when do_save() function failed? (for example when some data fails to validate)

like image 361
Kokizzu Avatar asked Sep 29 '13 00:09

Kokizzu


2 Answers

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;
    }   
like image 50
Bass Jobsen Avatar answered Sep 20 '22 07:09

Bass Jobsen


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.

like image 38
vogomatix Avatar answered Sep 20 '22 07:09

vogomatix