Unable to make auto focus on fields for bootstrap

2019-09-05 21:52发布

问题:

Hi so following this rails tutorial using coffeescript , a part of this function is suppose to find the bootstrap div modal, then find the "textarea" within it to auto focus it immediately .

ready = ->
    $(".media").on "click", -> 
        document.location = $(this).data("target")
        return false

    $(".modal").on "shown.bs.modal", ->
        $(this).find("textarea").focus()

$(document).ready(ready)
$(document).on "page:load", ready

The .media function click is working so far. However, another function which uses the shown.bs.modal is not working... I tried to Console.log or alert it as well but it seems that $(".modal").on "shown.bs.modal", is not working and i'm not sure why.

Here is my html

<div class="modal fade" tabindex="-1" role="dialog" id='new-question-modal'>
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">      <!--body of modal-->
        <!--Form body
        <form action="/questions" method="POST">-->

      <%=form_for :question,url: '/questions', html: {class: 'form-group'} do %>
        <div class="form-group">
          <label for="exampleInputEmail1">Email address</label>
          <input type="email"  name="question[email]" class="form-control" value = "<%= current_user_email%>" id="exampleInputEmail1" placeholder="Email">
        </div>

        <div class="form-group">
          <label for="inputQuestion" class="control-label">Question:</label>
          <textarea class="form-control"  name="question[body]" id="inputQuestion" placeholder="What would you like to know" required=""></textarea>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
      <%end%>
           <!--body of modal</form>-->
<!--Form body-->
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

From what i can tell it's suppose to identify the modal groups , and modal fade is one of them?

Below here is a sample of the webpage , where i click the green button and a form pops out which is the modal i took from bootstrap.

回答1:

Try: $(".modal').on "fade.in", -> $('input#exampleInputEmail1').focus();