Sasha
Sasha

Reputation: 8705

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.

Upvotes: 2

Views: 1600

Answers (3)

Sasha
Sasha

Reputation: 8705

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.

Upvotes: 1

Sean Wessell
Sean Wessell

Reputation: 3510

.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/

Upvotes: 1

Manuel
Manuel

Reputation: 416

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.

Upvotes: 0

Related Questions