I am using Bootstrap Switch with a simple on/off option.
How do I show a Bootstrap Modal asking for a confirmation once the user changes from on
to off
or from off
to on
?
Example 1 - User clicks to switch on
.
Modal: Are you sure you want to switch on?
Example 2 - User clicks to switch off
.
Modal: Are you sure you want to switch off?
I am able to set the modal on this jsfiddle but it's not working if the user clicks straight on the blue or gray color.
<div data-toggle="modal" data-target="#showModal">
Change status:
<input type="checkbox" class="switch" checked />
</div>
<!-- Modal -->
<div class="modal fade" id="showModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
This is the modal
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
I wonder why this issue. But I succeeded in creating a fix to your issue. Basically instead of allowing the div to target, you can listen to the switch event and use bootstrap's modal show/hide functions to show or hide your modal.
JavaScript:
$(document).ready(function () {
$("#myswitch").bootstrapSwitch();
$('#myswitch').on('switchChange.bootstrapSwitch', function (e, data) {
$('#showModal').modal('show');
});
});
HTML:
<div>
Change status:
<input type="checkbox" class="switch" id="myswitch" checked />
</div>
<!-- Modal -->
<div class="modal fade" id="showModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
This is the modal
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>