Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus Input Element on Modal Open Bootstrap 4

I am trying to autofocus input element on bootstrap 4 modal open . I have tried below code from http://getbootstrap.com/docs/4.0/components/modal/ but this is not working.

Can someone help me to give working demo

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').trigger('focus')
})
like image 670
Saurabh Mistry Avatar asked Dec 05 '22 12:12

Saurabh Mistry


1 Answers

Try the snippet below. Perhaps you need $(document).ready()

$(document).ready(function() {
  $('#myModal').on('shown.bs.modal', function() {
    $('#myInput').trigger('focus');
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />


<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <input type="text" class="form-control" id="myInput">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
like image 84
Dan Kreiger Avatar answered Mar 14 '23 20:03

Dan Kreiger