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

后端 未结 16 1084
感情败类
感情败类 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:44

    I found the best way to do this, without jQuery.

    <input value="" autofocus>
    

    works perfectly.

    This is a html5 attribute. Supported by all major browsers.
    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

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

    Use the autofocus to search for the right form element:

    $('.modal').on('shown.bs.modal', function() {
      $(this).find('[autofocus]').focus();
    });
    
    0 讨论(0)
  • 2020-12-07 15:46

    if you're looking for a snippet that would work for all your modals, and search automatically for the 1st input text in the opened one, you should use this:

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

    If your modal is loaded using ajax, use this instead:

    $(document).on('shown.bs.modal', '.modal', function() {
        $(this).find('input:visible:first').focus();
    });
    
    0 讨论(0)
  • 2020-12-07 15:46
    $(document).ready(function() {
      $("#button").click(function() {
        $('#mymodal').on('shown.bs.modal', function() {
          $('#myinput').focus();
        })
      });
    });
    
    • It is "#button" that calls the modal form,

    • "#mymodal" is the modal form,

    • "#myinput" is the input you want to get focus

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

    I got that bootstrap added the following info on their page:

    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:

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

    http://getbootstrap.com/javascript/#modals

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

    Try to remove the tabIndex property of the modal, when your input/textbox is open. Set it back to what ever it was, when you close input/textbox. This would resolve the issue irrespective bootstrap version, and without compromising the user experience flow.

    0 讨论(0)
提交回复
热议问题