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.
This will work but you might have to adjust the duration of the timeout and obviously the IDs where needed:
$("#ID-of-modal").on('show', function(event){
window.setTimeout(function(){
$(event.currentTarget).find('input#ID-of-input').first().focus()
}, 0175);
});
I don't know why, but the choosed solution doesn't work for me.. I use the following code snippet instead:
$('#annul-modal').on('show', function() {
setTimeout(function() {$('textarea:first', '#annul-form').focus();}, 400);
});
I know it isn't so pretty but at least it works.. Bootstrap v2.3.0
Attaching the event directly to the modal screen didn't work for me. I'm using this code instead:
$('body').on('shown.bs.modal', '.modal', function () {
$('[id$=myField]').focus();
})
With this code I only need to change myField for the id of the control I want to have the focus, it also allows me to define the focus for multiple modal screens, I have something like:
$('body').on('shown.bs.modal', '.modal', function () {
$('[id$=YesCancel]').focus();
$('[id$=YesInverted]').focus();
$('[id$=cancelAddCustomer]').focus();
$('[id$=closeHistoryModal]').focus();
});
Source http://xcellerant.net/2014/08/06/set-focus-on-a-field-when-showing-a-bootstrap-3-modal/
I wanted something a bit more generic
$(window.document).on('shown.bs.modal', '.modal', function () {
var timer = window.setTimeout(function () {
$('.firstInput', this).focus();
typeof timer !== 'undefined' && window.clearTimeout(timer);
}.bind(this), 100);
});
With this, I give whatever control I want the CSS class firstInput. There is a slight delay in setting focus that gives it a certain flair.
Bootstrap3
$(window.document).on('shown.bs.modal', '.modal', function() {
window.setTimeout(function() {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
Bootstrap 2
$(window.document).on('shown', '.modal', function() {
window.setTimeout(function() {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
<a href="" id="btnmoverCategoriaRaiz">Mover para a raiz...</a>
<script>
$(function(){
$("#btnmoverCategoriaRaiz").click(function(){
$("#novoPlaylist").modal();
return false;
});
});
</script>
<div id="novoPlaylist" class= "modal hide">
<div class="modal-header">
<h3>Novo Playlist</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<?echo $form->input("Playlist.nome", array("label"=>"Nome:")) ?>
</form>
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn" data-dismiss="modal">Cancelar</a>
<a href="javascript:;" class="btn btn-primary" id="SalvarNomePlaylist" data-loading-text="Aplicando..."> Savar</a>
</div>
</div>