Twitter bootstrap - Focus on textarea inside a modal on click

后端 未结 13 777
执笔经年
执笔经年 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: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/

提交回复
热议问题