Set focus to a button inside bootstrap modal when it opens

12,031

You are using show.bs.modal which Occurs when the modal is about to be shown

I believe you need shown.bs.modal event which Occurs when the modal is fully shown along when all the CSS transitions are completed.

See Bootstrap modal reference.

Share:
12,031
Ev.
Author by

Ev.

Updated on June 05, 2022

Comments

  • Ev.
    Ev. about 2 years

    I am trying to achieve the following:

    1. When the page loads, the focus goes to the first element in the form.
    2. When the button is pressed on form, a modal appears to confirm and the focus should be on the "Proceed" button inside modal dialog.

    I managed to to make the first one work, but for the second I have no idea why it is not working. Following is my code.

    HTML

    <form method="post" {% if action %} action="{{ action }}" {% endif %} role="form" enctype="multipart/form-data">
    <!-- Modal -->
      <div class="modal fade" id="confirmationModal" 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">Confirmation</h4>
            </div>
            <div class="modal-body">
               {{ confirm | default: "Would you like to proceed?" }}
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="submit" id="submit-main-form" class="btn btn-primary">
                  <i class="fa fa-save"></i> {{ submit_text | default: "Proceed" }}
              </button>
            </div>
          </div>
        </div>
      </div>
    
    </form>
    

    Script

    /* Sets focus on the first element of the form */
    $(document).ready(function() {
    
        $('form:first *:input[type!=hidden]:first').focus();
    
        $("#confirmationModal").on('show.bs.modal', function(event) {
            // not setting focus to submit button
            $("#submit-main-form").focus();
        });
    });