javascriptjquerytwitter-bootstraptwitter-bootstrap-3

Bootstrap modal hide is not working


Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.

<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>



<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>

bootply


Solution

  • 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>