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

后端 未结 16 1118
感情败类
感情败类 2020-12-07 15:12

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 happenin

相关标签:
16条回答
  • 2020-12-07 15:53

    If you want to just auto focus any modal that was open you can put in you patterns or lib functions this snippet that will focus on the first input:

    $('.modal').on('shown.bs.modal', function () {
      $(this).find('input:first').focus();
    })
    
    0 讨论(0)
  • 2020-12-07 15:54

    The usual code (below) does not work for me:

    $('#myModal').on('shown.bs.modal', function () {
      $('#myInput').focus()
    })
    

    I found the solution:

    $('body').on('shown.bs.modal', '#myModal', function () {
        $('input:visible:enabled:first', this).focus();
    })
    

    see more here

    0 讨论(0)
  • 2020-12-07 15:54

    this is the most general solution

    $('body').on('shown.bs.modal', '.modal', function () {
        $(this).find(":input:not(:button):visible:enabled:not([readonly]):first").focus();
    });
    
    • works with modals added to DOM after page load
    • works with input, textarea, select and not with button
    • ommits hidden, disabled, readonly
    • works with faded modals, no need for setInterval
    0 讨论(0)
  • 2020-12-07 15:54

    According to Bootstrap 4 docs:

    Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript.

    E.g:

    $('#idOfMyModal').on('shown.bs.modal', function () {
        $('input:first').trigger('focus')
    });
    

    Link.

    0 讨论(0)
  • 2020-12-07 15:55

    The answer of David Taiaroa is correct, but doesn’t work because the time to "fade in" the modal doesn’t let you set focus on input. You need to create a delay:

    $('#myModal').on('shown.bs.modal', function () {
        ...
        setTimeout(function (){
            $('#textareaID').focus();
        }, 1000);
    
    })
    
    0 讨论(0)
  • 2020-12-07 16:01

    First step, you have to set your autofocus attribute on form input.

    <input name="full_name" autofocus/>
    

    And then you have to add declaration to set autofocus of your input after your modal is shown.
    Try this code :

    $(document).on('ready', function(){
        // Set modal form input to autofocus when autofocus attribute is set
        $('.modal').on('shown.bs.modal', function () {
            $(this).find($.attr('autofocus')).focus();
        });
    });
    
    0 讨论(0)
提交回复
热议问题