Search code examples
twitter-bootstrapbuttonmodal-dialogbootstrap-switch

NO/YES iOS like button with modal on YES


How can I create iOS like sliding button with NO/YES state, which opens modal window when it's on YES?

Can this be done with bootstrap?

I found this code that I could use but I need someone to edit JS code so that modal only is shown on button YES state.

Fiddle

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">&times;</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>

JS

 $(document).ready(function() {
   $("#myswitch").bootstrapSwitch();

   $('#myswitch').on('switchChange.bootstrapSwitch', function(e, data) {
     $('#showModal').modal('show');
   });
 });

Solution

  • Yes it can be done with bootstrap,

    Add data attributes data-off-text="No" data-on-text="Yes" to replace OFF and ON

    <div>
      Change status:
      <input type="checkbox" class="switch" id="myswitch" checked="" data-off-text="No" data-on-text="Yes"/>
    </div>
    

    All you need is to check the bootstrap switch state if true and show the modal

    $(document).ready(function() {
        $("#myswitch").bootstrapSwitch();
    
        $('#myswitch').on('switchChange.bootstrapSwitch', function(event, state) {
            if (state == true) {
                $('#showModal').modal('show');
            }
        });
    });
    

    Fiddle

    SideNote: Optionally, the state of bootstrap swtich reset to false when modal closed with boostrap modal event listener, so no need to click on switch to reset it's state.

        $('#showModal').on('hide.bs.modal', function() {
            $("#myswitch").bootstrapSwitch('state', false, true);
        });
    

    Fiddle With Modal Event Listener