1

How can I auto focus an input on modal show? Currently I do this but it isn't working:

jQuery(document).ready(function($) {
    $('#myModal').on('show.bs.modal', function() {
        $('input[name="myInput"]').focus();
    });
});

http://jsfiddle.net/1aeur58f/2513/

eisbehr
  • 12,243
  • 7
  • 38
  • 63
steve
  • 471
  • 6
  • 15
  • 1
    Possible duplicate of [How to Set focus to first text input in a bootstrap modal after shown](https://stackoverflow.com/questions/15247849/how-to-set-focus-to-first-text-input-in-a-bootstrap-modal-after-shown) – 31piy Apr 05 '18 at 07:20
  • 2
    Possibly you want shown.bs.modal instead of show.bs.modal? – AaronHolland Apr 05 '18 at 07:21

2 Answers2

7

Your code is basically correct. But the event show.bs.modal is triggerede before the modal has been shown. You need to use shown.bs.modal event instead.

jQuery(function($) {
    $('#myModal').on('shown.bs.modal', function() {
        $('input[name="myInput"]').focus();
    });
});

http://jsfiddle.net/1aeur58f/2544/

eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • `$('input[name="myInput"]').focus();` did not work for me, but `$('#myInput').focus();` did work - thanks! (Bootstrap 4) – cloudxix Jun 14 '22 at 05:01
0

In Your code, Use autofocus

<input name="myInput" value="MyVal" type="text" autofocus/>

Sudarshan
  • 367
  • 2
  • 8
  • 20