The focus() method of the Textarea object gives the focus to the text area. Be careful when using this method in conjunction with the Textarea. blur() method. It can lead to a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice versa.
@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();
})
I found the best way to do this, without jQuery.
<input value="" autofocus>
works perfectly.
This is a html5 attribute. Supported by all major browsers.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input
The answer of David Taiaroa is correct, but doesn’t work because the time to "fade in" the modal doesn’t let you set focus on input. You need to create a delay:
$('#myModal').on('shown.bs.modal', function () {
...
setTimeout(function (){
$('#textareaID').focus();
}, 1000);
})
The usual code (below) does not work for me:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
I found the solution:
$('body').on('shown.bs.modal', '#myModal', function () {
$('input:visible:enabled:first', this).focus();
})
I got that bootstrap added the following info on their page:
Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
http://getbootstrap.com/javascript/#modals
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With