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

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


Asked on November 1, 2018 in Bootstrap.
Add Comment

  • 1 Answer(s)

    To set focus on input field, jQuery .focus() method is used.

    Here the jQuery .focus() method is used to set focus on the first input box or textarea inside the Bootstrap modal when its load upon activation.
    For example:

    <!DOCTYPE html>
    <html lang="en">
    <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=""></script>
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $("#myModal").on('', function(){
        <!-- 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 class="modal-body">
                            <div class="form-group">
                                <label for="inputName">Name</label>
                                <input type="text" class="form-control" id="inputName">
                            <div class="form-group">
                                <label for="inputComment">Comments</label>
                                <textarea class="form-control" id="inputComment" rows="4"></textarea>
                    <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>

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

    Answered on November 1, 2018.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.