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

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

    @scumah has the answer for you: Twitter bootstrap - Focus on textarea inside a modal on click

    For Bootstrap 2

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

    Update: For Bootstrap 3

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

    ========== Update ======

    In response to a question, you can use this with multiple modals on the same page if you specify different data-targets, rename your modals IDs to match and update the IDs of the form input fields, and finally update your JS to match these new IDs:
    see http://jsfiddle.net/panchroma/owtqhpzr/5/

    HTML

    ...
    <button ... data-target="#myModal1"> ... </button> 
    ... 
    <!-- Modal 1 -->
    <div class="modal fade" id="myModal1" ...>
    ... 
    
    <div class="modal-body"> <textarea id="textareaID1" ...></textarea></div>
    

    JS

    $('#myModal1').on('shown.bs.modal', function() {
      $('#textareaID1').focus();
    })
    
    0 讨论(0)
  • 2020-12-07 16:05

    This is the simple code that will work for you best on all popups that has any input field with focusing it

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

    try this code, it might work for you

    $(this).find('input:text')[0].focus();
    
    0 讨论(0)
  • 2020-12-07 16:08

    I think the most correct answer, assuming the use of jQuery, is a consolidation of aspects of all the answers in this page, plus the use of the event that Bootstrap passes:

    $(document).on('shown.bs.modal', function(e) {
      $('input:visible:enabled:first', e.target).focus();
    });
    

    It also would work changing $(document) to $('.modal') or to add a class to the modal that signals that this focus should occur, like $('.modal.focus-on-first-input')

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