最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select text input when bootstrap modal open - Stack Overflow

programmeradmin0浏览0评论

I have a input inside of a bootstrap modal. When the modal is opened, I want the input that that is inside the bootstrap modal to be automatically selected.

I have the following code:

$('#modal').on('show.bs.modal', function (e) {
   $(this).$("input").select();
})

and my modal looks like:

<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
       <div class="modal-body">
         <input type='text' disabled value="test">
       </div>
    </div>
  </div>
</div>

Unfortunately, with this code, I'm getting the error "Uncaught TypeError: undefined is not a function "

I have a input inside of a bootstrap modal. When the modal is opened, I want the input that that is inside the bootstrap modal to be automatically selected.

I have the following code:

$('#modal').on('show.bs.modal', function (e) {
   $(this).$("input").select();
})

and my modal looks like:

<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
       <div class="modal-body">
         <input type='text' disabled value="test">
       </div>
    </div>
  </div>
</div>

Unfortunately, with this code, I'm getting the error "Uncaught TypeError: undefined is not a function "

Share Improve this question asked May 28, 2014 at 4:33 the_the_ 1,1733 gold badges30 silver badges63 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Use .find() and then .focus()

$('#modal').on('show.bs.modal', function (e) {
   var input = $(this).find("input");  // cache the variable
   input.removeAttr('disabled'); // enable it first, so it can get focus
   input.focus(); // focus it
})

and then use .focus() to focus the element. There is nothing called .select() in jQuery core.

what worked for me:

$('#modal').on('shown.bs.modal', function (e) {
    $('#modal input[type="text"]')[0].select();
});

note the use of .on('shown.bs.modal'), not .on('show.bs.modal')

try

$('#modal').on('show.bs.modal', function (e) {
   var input= $(this).find("input");
   if(input){
       input.removeAttr('disabled');
       input.focus();
   }
})
发布评论

评论列表(0)

  1. 暂无评论