How to Set focus to first text input in a bootstrap modal after shown

因為彈出的modal 就是要去填資料, 但每次都要多用滑鼠點一點, 覺得很麻煩, 希望彈出 modal 後, 可以讓游標停在第一個輸入欄位. 解法:

Your code is basically correct. But the event show.bs.modal is triggerede before the modal has been shown. You need to use shown.bs.modal event instead.

jQuery(function($) {
    $('#myModal').on('shown.bs.modal', function() {
        $('input[name="myInput"]').focus();
    });
});

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();
})

資料來源:
https://stackoverflow.com/questions/15247849/how-to-set-focus-to-first-text-input-in-a-bootstrap-modal-after-shown


實測, 上面的方法都無效, 應該是年代久遠, bootstrap 改版, 官方提供的解法:
https://getbootstrap.com/docs/5.3/components/modal/

const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', () => {
  myInput.focus()
})

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *