Ad

How To Set Focus On Input In Modal?

- 1 answer

I'm trying to set focus on an input after the modal shows.

The solutions and links I've seen and tried so far: How to focus on a form input text field on page load using jQuery?, Jquery Focus on input field, and none of them works.

My code is actually pretty simple:

$input = $("#letter-change-text").find("input[type='text']");
$input.val($.trim("I am just testing!!"));
$("#letter-change-text").modal('show');
$input.focus(); // this should focus the textbox in order to allow immediately input by the user

You can check this issue in JSfiddle.

I also have tried without any success:

setTimeout(function(){
   $input.focus();
}, 0);
Ad

Answer

Use the shown event

$(function(){
    $input = $("#letter-change-text").find("input[type='text']");
    $input.val($.trim("I am just testing!!"));
    $('#letter-change-text').on('shown.bs.modal', function (e) {
       $input.focus();
    }).modal('show');
});
Ad
source: stackoverflow.com
Ad