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.
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()
})
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.
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/
You can use the autofocus
html element to set the autofocus.
<textarea id="textareaID" autofocus="" ></textarea>
Fiddle here (Click)
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);
});
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>