Set Focus on a Field when Showing a Bootstrap 3 Modal

While testing an application that I’m working on, I noticed that the focus is not set on a field within a Bootstrap modal when it’s shown. This is annoying to the user because it requires to tab a number of times (since the focus stays on the button clicked to show the modal) or click into a field in order to start typing. In this post, I’ll show how to force the focus to be set on a specific field when a modal is shown.

Event Delegation

One simple approach is to use jQuery event delegation (here’s a great explanation from Mark Roden). An event handler can be added to the body tag to fire whenever a modal is shown. Within that handler, we can set the focus on a specific field.

$('body').on('shown.bs.modal', '.modal', function () {
  $('[id$=myField]').focus();
})

The first line sets up the event delegation by adding a listener to the body of the page for the event of showing a modal (shown.bs.modal). The second line locates the field named myField and sets focus on it.

The selector in the second line may look a bit strange, but it’s effect is to find the element where the id attribute ends with myField. This is because XPages adds a number of colon-separated prefixes to each element, depending on it’s depth in the page structure. In order to not worry about all of that, the code looks for the element that ends with the name that I assigned to the field.

Here are two other options that you have for achieving the same effect:

  1. Add a unique class name to the field and use $(‘.yourClassName’) as the selector
  2. Use Mark Roden’s x$() function to select an element

Modals and Partial Refreshes

As if there haven’t already been enough (too many?) references to Marky, take a look at this post if you have a modal that needs to perform partial refreshes.

Ultimately, the code I’m actually using in my application looks like this:

$('body').on('shown.bs.modal', '.modal', function () {
  $('FORM').append($('.modal'));
  $('[id$=myField]').focus();
})

Multiple Modals

This method works fine on a page that only has one modal. If you have multiple modals, you’d need to adjust the logic in order to set the field focus as desired. One more generic option would be to change the jQuery selector to just find the first input field on the modal.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: