I load a dynamic bootstrap modal and it contains few text inputs. The issue i face that i want the cursor to focus on the first input in this modal, and this is not happenin
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
Use the autofocus to search for the right form element:
$('.modal').on('shown.bs.modal', function() {
$(this).find('[autofocus]').focus();
});
if you're looking for a snippet that would work for all your modals, and search automatically for the 1st input text in the opened one, you should use this:
$('.modal').on('shown.bs.modal', function () {
$(this).find( 'input:visible:first').focus();
});
If your modal is loaded using ajax, use this instead:
$(document).on('shown.bs.modal', '.modal', function() {
$(this).find('input:visible:first').focus();
});
$(document).ready(function() {
$("#button").click(function() {
$('#mymodal').on('shown.bs.modal', function() {
$('#myinput').focus();
})
});
});
It is "#button" that calls the modal form,
"#mymodal" is the modal form,
"#myinput" is the input you want to get 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
Try to remove the tabIndex property of the modal, when your input/textbox is open. Set it back to what ever it was, when you close input/textbox. This would resolve the issue irrespective bootstrap version, and without compromising the user experience flow.