Ev. Ev. - 1 year ago 166
jQuery Question

Set focus to a button inside bootstrap modal when it opens

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.


<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>
<h4 class="modal-title" id="myModalLabel">Confirmation</h4>
<div class="modal-body">
{{ confirm | default: "Would you like to proceed?" }}
<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" }}



/* 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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download