bootstrap tutorial - How to set focus on input field or textarea inside a Bootstrap modal on activation - bootstrap examples - bootstrap templates - bootstrap 3



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:

Example

<!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">×</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>
click below button to copy the code. By - Bootstrap tutorial - team

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 Searches to How to set focus on input field or textarea inside a Bootstrap modal on activation