admin管理员组

文章数量:1355520

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();
    });
});

/

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/1aeur58f/2513/

Share Improve this question edited Apr 5, 2018 at 7:49 eisbehr 12.5k7 gold badges41 silver badges65 bronze badges asked Apr 5, 2018 at 7:18 steve steve 4831 gold badge6 silver badges18 bronze badges 2
  • 1 Possible duplicate of How to Set focus to first text input in a bootstrap modal after shown – 31piy Commented Apr 5, 2018 at 7:20
  • 2 Possibly you want shown.bs.modal instead of show.bs.modal? – AaronHolland Commented Apr 5, 2018 at 7:21
Add a ment  | 

3 Answers 3

Reset to default 8

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/1aeur58f/2544/

In Your code, Use autofocus

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

For Bootstrap 5:

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

For WordPress:

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

本文标签: javascriptFocus input on modal showStack Overflow