How to Focus on the Input Dialog Box in Bootstrap

Here is an easy way after pressing the button so that when the dialog box appears, it will immediately focus on the initial input. Just put a jQuery codes to your JS script. Works well on FF, Chrome and Android browsers and multiple dialog boxes on one page.

Example:

HTML

<!--YOUR BUTTON-->
<button class="btn btn-sm btn-primary" data-target="#mdlSomething" data-toggle="modal"><i class="fa fa-fw fa-plus small"></i> Add Something</button>
 
<!--YOUR DIALOG-->
    <div aria-hidden="true" aria-labelledby="mdlSomethingLabel" class="modal" id="mdlSomething" role="dialog" tabindex="">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <p class="modal-title text-muted"><b>My Something</b></p>
            <button aria-label="Close" class="close text-white" data-dismiss="modal" type="button">
              <span aria-hidden="true">�-</span>
            </button>
          </div>
          <div class="modal-body">
            <form>
              <div class="form-group">
                <small class="form-text pb-0 mb-0 text-muted"><b>Name of what</b></small>
                <input aria-describedby="nameofwhat" class="form-control" id="nameofwhat" type="text" />
              </div>
              <div class="form-group">
                <small class="form-text pb-0 mb-0 text-muted"><b>Name of something</b></small>
                <input class="form-control" id="nameofsomething" type="text" />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button class="btn btn-sm btn-secondary" data-dismiss="modal" type="button"><i class="fas fa-times-circle"></i> Close</button>
            <button class="btn btn-sm btn-primary" type="button"><i class="fas fa-save"></i> Save</button>
          </div>
        </div>
      </div>
    </div>
JS
(function($) {
  "use strict";
  $('.modal').on('shown.bs.modal', function() {
    $('.modal-body').find('*').filter(':input:visible:first').trigger('focus');
  });
})(jQuery);

0 comments:

Post a Comment