How to prevent a mode from appearing?

0

Is it possible to prevent a modal from appearing if certain conditions are met? Example of what I want, more or less:

<button id="abreModal" class="btn btn-info btn-lg" data-toggle="modal" data-target="#modal">Open Modal</button>

//aí no js...
$('#abreModal').click(function () {
   if(condicao){
        // ... previne modal de abrir
   }
});

I know if I take the data-toggle and data-target, and show the modal manually, I can. But I have several buttons like that, and I do not want to have to change them all.

    
asked by anonymous 24.10.2017 / 20:20

2 answers

2

If the click event opens the modal is very simple to do is just do so:

$('.btn').click(function () {
   if(condicao){
        return false;
   }
   // Seu código para abrir o modal.
});

So if the condition is true it will not do anything, you can put an alert for example on 'return false' to send a message to the user.

Example: link

    
24.10.2017 / 20:24
1

There is an option using the bootstrap events, not so viable, but to adapt:

$('.modal').on('shown.bs.modal',function(e){
   var button = $(e.relatedTarget);
   var target = button.data('target')
   //condição
   var i = 4;
   //if
   if(i > 2){
       $(target).modal('toggle')
   }
})
<script src="https://code.jquery.com/jquery-3.2.1.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>
    
24.10.2017 / 20:42