1

I need to have the focus for textfield in a twitter bootstrap modal dialog.I have tried the focus() method.

DEMO

$('#openBtn').click(function(){
    $('#myModal').modal({show:true});
  initialize();
});
function initialize(){

    $('#my').val('');/*empty the textfield for each time
    dialog is called */
   $('#my').focus();//to get focus
}

HTML:

<a href="#" class="btn btn-default" id="openBtn">Open modal</a>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
            <h3>Modal header</h3>
    </div>
    <div class="modal-body">

        <input type="text" id="my" value="">
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Close</button>
    </div>
    </div>
</div>
</div>
codingBliss
  • 135
  • 5
  • 18
  • Might be a duplicate [here](http://stackoverflow.com/questions/15247849/how-to-set-focus-to-first-text-input-in-a-bootstrap-modal-after-shown), Though I did try implementing the solution with your Bootply and it didn't help. I'll keep looking into it. – Jonathan May 29 '14 at 14:46

2 Answers2

2

So, here are a few pointers. With Bootstrap 3.x there is a function that is triggered by the modal.shown event called thusly, $('#myModal').on('shown.bs.modal', funciton() {...}) which is used to do what your initialize() function is doing. To fix the issue with focus() you have to add the following line to your code:

$("#my").ready(function() {...})

The problem is that the input isn't fully ready in the DOM, so you must wait for it to be loaded and ready before you try manipulating it. Here is more documentation on the .ready() function.

Here is the DEMO

Jonathan
  • 1,126
  • 10
  • 19
  • If this solution is what you are looking for, please accept the answer :) ps. Thanks for the challenge. I've never run into this bug before. I've always relied on the solution [mentioned](http://stackoverflow.com/a/15252413/2041091) – Jonathan May 29 '14 at 16:46
  • thanks for the well researched solution. I improvised on the solution and textfield is first made empty before the ready function.[link](http://jsfiddle.net/DLgDp/2/) – codingBliss May 29 '14 at 17:37
1

Code Snippet for showing the dialog

$('#openBtn').click(function () {
    $('#myModal').modal({show:true});
    $('#my').val('');//empting the textfield so that dialog does not retain previous state
}); 

not using the ready function,using only modal shown event

$('#myModal').on('shown.bs.modal', function () {
        $("#my").focus();
});

DEMO

codingBliss
  • 135
  • 5
  • 18
  • I feel like this was just one of those 'Duh...' moments... I can't believe I didn't see this earlier. Thanks for posting this after the fact! – Jonathan May 29 '14 at 19:03