Amr Elgarhy Amr Elgarhy - 6 months ago 160x
Javascript Question

How to Set focus to first text input in a bootstrap modal after shown

I load a dynamic bootstrap modal and it contains few text inputs. The issue i face that i want the cursor to focus on the first input in this modal, and this is not happening by default.

So i wrote this code to do it:

$('#modalContainer').on('show', function () {

But now it focus on the in the input for a moment then go away automatically, why this is happening and how to solve?


@scumah has the answer for you: Twitter bootstrap - Focus on textarea inside a modal on click

For Bootstrap 2

modal.$el.on('shown', function () {
$('input:text:visible:first', this).focus();

Update: For Bootstrap 3

$('#myModal').on('', function () {

========== Update ======

In response to a question, you can use this with multiple modals on the same page if you specify different data-targets, rename your modals IDs to match and update the IDs of the form input fields, and finally update your JS to match these new IDs:


<button ... data-target="#myModal1"> ... </button> 
<!-- Modal 1 -->
<div class="modal fade" id="myModal1" ...>

<div class="modal-body"> <textarea id="textareaID1" ...></textarea></div>


$('#myModal1').on('', function() {