Twitter bootstrap - Focus on textarea inside a modal on click

后端 未结 13 729
执笔经年
执笔经年 2020-11-30 22:46

Just starting to play around with bootstrap and it\'s amazing.

I\'m trying to figure this out. I have a textarea for feedback inside a modal window. It works great.

相关标签:
13条回答
  • 2020-11-30 23:29

    If you are using bootstrap v3 and you are using both modal dialog and wysihtml5 text editor the following works (assuming #basic is the ID of your modal form):

        $('#basic').on('shown.bs.modal', function () {
        editor.composer.element.focus()
    })
    
    0 讨论(0)
  • 2020-11-30 23:31

    Found doing:

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

    Worked well as it just finds the first form-control rather than needing a specific id etc. Be just what is needed most of the time.

    0 讨论(0)
  • 2020-11-30 23:32

    It doesn't work because when you click the button the modal is not loaded yet. You need to hook the focus to an event, and going to the bootstrap's modals page we see the event shown, that is fired when the modal has been made visible to the user (will wait for css transitions to complete). And that's exactly what we want.

    Try this:

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

    Here's your fiddle updated: http://jsfiddle.net/5JN9A/5/


    Update:

    As @MrDBA notes, in Bootstrap 3 the event name is changed to shown.bs.modal. So, for Bootstrap 3 use:

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

    New fiddle for Bootstrap 3: http://jsfiddle.net/WV5e7/

    0 讨论(0)
  • 2020-11-30 23:38

    You can use the autofocus html element to set the autofocus.

    <textarea id="textareaID" autofocus="" ></textarea>
    

    Fiddle here (Click)

    0 讨论(0)
  • 2020-11-30 23:38

    I was having major issues in chrome... I hope this helps someone.

    //When user clicks link
    $('#login-modal-link').on('click',function() {
            setTimeout(function(){
                    //If modal has class
                if ($('#login-modal').hasClass('modal')) {
                    //Whatever input you want to focus in
                    $('#user_login_modal').focus();
                }
            },100);
    
        });
    
    0 讨论(0)
  • 2020-11-30 23:38

    As mentioned in one of the comments you need to remove fade from your modal. So this works for me:

     <div id="myModal" class="modal">
        ...
        <textarea class="form-control" rows="5" id="note"></textarea>
      </div>
    
      <script>
        $('#myModal').on('shown.bs.modal', function () {
            $('#note').focus();
        })
      </script>
    
    0 讨论(0)
提交回复
热议问题