简体   繁体   中英

Select text input when bootstrap modal open

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 "

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM