简体   繁体   中英

Jquery, Bootstrap - trigger click event on modal hide and select text in input

How can I select text inside input when the modal is closed? Below code is working - when I click the input field, alert is coming up and text is selected. On modal hide event alert is shown, but the text is not selected. What is going on here?

JS Code:

// Sellect text
$('.user').on('click', '#name', function(){
        $(this).select();
        alert(1);
    });
$('#myModal').on('hide.bs.modal', function(){

    $('.user').find('#name').trigger('click');

});

HTML

<div class="user">
  <p>Name
        <input type="text" name="name" id="name" value="<?php echo $user->name ?>" readonly="readonly">
  </p>
</div>

SOLUTION

I found out that instead of using hide.bs.modal event, I should use hidden.bs.modal event. In that case the script is working.

.focus doesn't work for some reason it will not allow you to focus the element until the modal is fully unloaded. I even tried changing the event to hidden.bs.modal that fires after hide.bs.modal and it doesn't matter.

A workaround i have found is to use setInterval and check to see if the body has class "modal-open" once it doesn't then fire focus event

$('#myModal').on('hidden.bs.modal', function() {
  var waitForClose = window.setInterval(function() {
    if ($('body').hasClass('modal-open') == false) {
      $('.user').find('#name').trigger('focus');
      window.clearInterval(waitForClose)
    }
  }, 100);
});

http://jsfiddle.net/SeanWessell/61sc4Ldr/

I found out that instead of using hide.bs.modal event, I should use hidden.bs.modal event. In that case the script is working.

Not sure where is the text field you're referring to. In the modal element or not. Assuming you already specified in the script that the document is ready ( $(document).ready(..) , or loaded that script after the html elements are created in the html) You can try calling $( "#name" ).focus(function() { $(this).select(); } ); in the close event.

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