简体   繁体   中英

OK and Cancel in a bootstrap modal

I would like to implement a classic OK and Cancel concept in a bootstrap modal.

<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">
      user can select an option here from a list
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
    <button type="button" class="btn btn-primary">OK</button>
  </div>
</div>

In the model content, there is a and the user can select one of the options. If OK is clicked, I would like to handle the new option. If not, no action is required. For that I hook on the hide.bs.modal event, but that is called when Cancel is clicked.

How can I differentiate between Cancel and OK buttons?

Well, Bootstrap does not support specific modal events for the modal actions buttons. So, I believe you will have to handle the events yourself like so.

    $("#myModal").on("click",".btn-default", function(){
       // code
    });

    $("#myModal").on("click",".btn-primary", function(){
       // code
    });

You can simply add an click event to OK button? If you do not add e.preventDefault() to your event you can process normally.

First add your OK button a definitive ID or class name:

<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">
      user can select an option here from a list
      <select name="select" id="select1">
        <option value="1">1</option>
        <option value="2" selected="selected">2</option>
        <option value="3">3</option>
      </select>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
      <button type="button" id="btn_ok_1" class="btn btn-primary">OK</button>
    </div>
  </div>
</div>

Then add a click event to that button:

$("#btn_ok_1").click(function (e) {
  var selectedOption = $('select#select1 option:selected').val;

  // Do some work with selected item.
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM