modal bootstrap close with enter

2

I have the modal sig but it only closes when the button is clicked I also want it to close when press enter, thanks

<div class="container">
<!-- Modal -->
<div class="modal fade" id="ModalRetencion" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4> <label style="margin-left:25%;"  id="soyla"></label> </h4>
        <div class="modal-footer">
        <button style="margin-left:30%;"  type="submit" class="btn btn-danger  pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Aceptar</button>
      </div>
     </div>
    <div class="modal-body" >
  </div>
  </div>
</div>

    
asked by sanlegas 13.10.2018 в 00:26
source

1 answer

3

You can know when a modal has been shown with the event 'shown.bs.modal', here I leave the link to see the events of the modal.

$('#exampleModal').on('shown.bs.modal', function (e) {

});

Once you assign your DOM event, through the 'keydown' event of jQuery you can know when a key was pressed, the enter has a numerical value of 13, so we ask for that value.

$(this).keydown(function(e){
    if(e.which == 13) {
        $('#exampleModal').modal('hide');
    }
});

And to hide the modal simply:

$('#exampleModal').modal('hide');

The complete code would be:

$(document).ready(function(){
    $('#exampleModal').on('shown.bs.modal', function (e) {
      $(this).keydown(function(e) {
        if(e.which == 13) {
          $('#exampleModal').modal('hide');
        }
      });
    });
});

Here I'll give you the complete example.

    
answered by 13.10.2018 / 01:39
source