1

When I open this Modal, I need to take the cursor to the textbox using the mouse

So I want to focus() on the textbox as soon as the modal opens.

Css and JS files

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

Javascript Code

<script type="text/javascript">
    $(document).ready(function(){
        $('.launch-modal').click(function(){
            $('#myModal').modal({
                backdrop: 'static'
            });
        // document.form1.focushere.focus();
    }); 
    });
</script>

HTML Code

<body>
    <form name="form1">
        <!-- Button HTML (to Trigger Modal) -->
        <input type="button" class="btn btn-lg btn-primary launch-modal" value="Launch Demo Modal">

        <!-- Modal HTML -->
        <div id="myModal" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Confirmation Box</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="text" id="" name="focushere">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>                             
Community
  • 1
  • 1
  • does this help? https://stackoverflow.com/questions/26021493/how-to-set-focus-on-input-in-modal – Nikki9696 Jan 08 '19 at 22:04
  • also i like this one, it uses a simple open event for the dialog https://stackoverflow.com/questions/6291585/jquery-ui-modal-dialog-set-focus-on-first-form-element – Nikki9696 Jan 08 '19 at 22:05

1 Answers1

0

Essentially it doesn't work because the modal is not loaded so there isn't any field that Javascript could hold on to.

You can modify the code to do something like this:

  $('#myModal').on('shown.bs.modal', function() {
    document.form1.focushere.focus();
  })

It will run the focus() function when the modal is loaded.

See this answer: Twitter bootstrap - Focus on textarea inside a modal on click

Cesar Correchel
  • 513
  • 3
  • 7