2

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.

Sasha
  • 8,521
  • 23
  • 91
  • 174

3 Answers3

1

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

Sean Wessell
  • 3,490
  • 1
  • 12
  • 20
  • Thanks for the answer - I just changed to the **hidden.bs.modal** event, and the script is working without any problems. – Sasha Dec 10 '15 at 17:14
1

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.

Sasha
  • 8,521
  • 23
  • 91
  • 174
0

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.

Manuel
  • 366
  • 2
  • 7
  • Ok. Here is a [thread](http://stackoverflow.com/questions/3150275/jquery-input-select-all-on-focus) I found that might help with that. I assume you're in the correct path because the alert shows up, but something else minor is not making that happen. – Manuel Dec 10 '15 at 17:17