Focus on entry when Bootstrap Modal is closed

After the blur event in the "bootbox1" input field, I want to use the Bootstrap Modal to post a message after the modal focus closure goes to the "bootbox2" input field. But the input field is not focused.

What am I doing wrong?

Demo

Html

<input type="text" id="bootbox" />
<input type="text" id="bootbox2" />
<div id="myModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
        <!-- dialog body -->
        <div class="modal-body">
            <button type="button" class="close" data-dismiss="modal">&times;</button>Hello world!</div>
        <!-- dialog buttons -->
        <div class="modal-footer">
            <button type="button" class="btn btn-primary">OK</button>
        </div>
    </div>
  </div>
</div>

      

Js

$('#bootbox').on('blur', function checkSelection(e) {
  $("#myModal").on("show", function () { // wire up the OK button to dismiss the modal when shown
    $("#myModal a.btn").on("click", function (e) {
        console.log("button pressed"); // just as an example...
        $("#myModal").modal('hide');
        $('#bootbox2').focus();
        // dismiss the dialog
    });
  });

  $("#myModal").on("hide", function () { // remove the event listeners when the dialog is dismissed
    $("#myModal a.btn").off("click");
    $('#bootbox2').focus();
  });

  $("#myModal").on("hidden", function () { // remove the actual elements from the DOM when fully hidden
    $("#myModal").remove();
  });

  $("#myModal").modal({ // wire up the actual modal functionality and show the dialog
    "backdrop": "static",
        "keyboard": true,
        "show": true // ensure the modal is shown immediately
  });

});

//this works
$('#bootbox2').on('blur', function checkSelection(e) {
  $('#bootbox').focus();
});

      

+3


source to share


1 answer


You need to wait for the event hidden.bs.modal

, not hide.bs.modal

.

As per Bootstrap Docs for eventhide.bs.modal

This event fires immediately when the hide instance method has been called.



While hidden.bs.modal

This event is fired when modal completion is hidden from the user (will wait for CSS transitions to complete).

Since yours focus

is called before the overlay was removed, the input cannot yet receive keyboard focus.

+9


source







All Articles