How to close a modal by pressing the "ENTER" key

Asked

Viewed 524 times

0

How can I close a modal in bootstrap using the enter key:

the code I’m using is as follows::

<div class="modal fade" id="succes-action" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content modal-position-medium">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            @if (ViewBag.Success == true) {
                <h4 class="modal-title modal-title-bold" id="myModalLabel"><span class="modal-logo glyphicon glyphicon-ok-circle" aria-hidden="true"></span>Sucesso</h4>
            }
            else {
                <h4 class="modal-title modal-title-bold" id="myModalLabel"><span class="modal-logo error glyphicon glyphicon-remove-sign" aria-hidden="true"></span>Erro</h4>
            }
        </div>
        <div class="modal-body">
            @if (ViewBag.Success == true) {
                <p>Um email foi enviado para <b>@ViewBag.EmailLabel</b> contento instruções para redefinir sua senha.</p>
            }
            else {
                <p>Não foi possível enviar um email para <b>@ViewBag.EmailLabel</b> contento instruções para redefinir sua senha.</p>
                <p>Por favor, contate a equipe de suporte do sistema PRODANÇA.</p>
            }
        </div>
        <div class="modal-footer">
            <button type="button" data-dismiss="modal" aria-hidden="true" class="btn btn-primary btn-min-size">OK</button>
        </div>
    </div>
</div>

  • If my answer has helped you in any way, mark it as accepted.

1 answer

1


That way, the event keypress will be monitoring whenever any key is pressed, and when it is the enter (code 13), will close the modal.

$(document).ready(function() {
  $(document).on('keypress', function(e) {
    if(e.keyCode == 13) {
      $('.modal').modal('hide');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.