How to prevent bootstrap modal from loading from a button using onclick?

I have a modal with a button (Save)

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

how to prevent closure if do_save() function do_save() ? (for example, when some data is not checked)

+6
source share
3 answers

Do not use 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; } 
+17
source

Since you use jQuery anyway, try not to include JavaScript / jQuery 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> 

Alternatively, you can probably prevent closure by intercepting the "hide" event and returning it false.

+5
source

If you catch the click event from the button as follows:

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

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

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

If I understand this site (which is in German) http://www.mediaevent.de/javascript/event-handler-default-verhindern.html correctly, preventDefault () stops the immediate action by default (for example, by reference). However, the event itself will still pass through the DOM and can be "heard" by various event listeners, one of which is an event listener that hides the modal. This requires a second function that stops the event from moving through the DOM. Thus, he cannot be heard by a hiding listener, and the window will not be closed (hidden). Therefore, I propose to implement such functions:

  $('#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 need to use stopPropagation (), since my default action is required, so you can use two functions independently.

Note. This solution has only been tested with Firefox.

+3
source

Source: https://habr.com/ru/post/954864/


All Articles