WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to set focus on input field or textarea inside a Bootstrap modal on activation

Topic: Bootstrap / LessPrev|Next

Answer: Use the jQuery .focus() method

You can use the jQuery .focus() method to set focus on the first input box or textarea inside the Bootstrap modal when its load upon activation, like this:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>Set Focus on First Text Input inside Bootstrap Modal</title>
  • <link rel="stylesheet" href="css/bootstrap.min.css">
  • <link rel="stylesheet" href="css/bootstrap-theme.min.css">
  • <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  • <script src="js/bootstrap.min.js"></script>
  • <script type="text/javascript">
  • $(document).ready(function(){
  •     $("#myModal").on('shown.bs.modal', function(){
  •         $(this).find('#inputName').focus();
  •     });
  • });
  • </script>
  • </head>
  • <body>
  •     <!-- Button HTML (to Trigger Modal) -->
  •     <a href="#myModal" class="btn btn-lg btn-primary" data-toggle="modal">Launch Demo Modal</a>
  •     
  •     <!-- Modal HTML -->
  •     <div id="myModal" class="modal fade">
  •         <div class="modal-dialog">
  •             <div class="modal-content">
  •                 <div class="modal-header">
  •                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  •                     <h4 class="modal-title">Your Feedback</h4>
  •                 </div>
  •                 <div class="modal-body">
  •                     <form>
  •                         <div class="form-group">
  •                             <label for="inputName">Name</label>
  •                             <input type="text" class="form-control" id="inputName">
  •                         </div>
  •                         <div class="form-group">
  •                             <label for="inputComment">Comments</label>
  •                             <textarea class="form-control" id="inputComment" rows="4"></textarea>
  •                         </div>
  •                     </form>
  •                 </div>
  •                 <div class="modal-footer">
  •                     <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
  •                     <button type="button" class="btn btn-primary">Send</button>
  •                 </div>
  •             </div>
  •         </div>
  •     </div>
  • </body>
  • </html>

The jQuery code in the above example simply finds the <input> element and set focus on it when modal is visible to the user using the modal's shown.bs.modal event.


Related FAQ

Here are some more FAQ related to this topic:

Your Feedback:

We would love to hear from you, please drop us a line.