My Bootstrap modal hide code is not working. The "else" alert appears, showing that I'm in the else statement, but my modal is not hidden as it should be after that. Why isn't the modal hiding properly?
$("#buy").click(function () {
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"/>
<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>
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>