简体   繁体   中英

How to focus form input field with Rails + Bootstrap + formtastic_bootstrap

I have an input form and I would like to set the keyboard focus when the page loads. I am using Rails with Bootstrap and I have formtastic_bootstrap for the forms. Here is a simplified example:

<%= semantic_form_for item, url:url_for_event(:create) do |f| %>
  <%= f.input :title, label: t('.title') %>
  <%= f.input :description, label: t('.description') %>
  <%= f.submit t('.create'), class: 'btn btn-primary pull-right' %>
<% end %>

I would like to focus the "title" field so that the cursor is in that field and the Bootstrap blue highlight appears when the page loads so that the user can just start typing into that field.

I have tried setting "autofocus" on the field like this

<%= f.input :title, label: t('.title'), input_html: { autofocus: true } %>

I have tried with jquery

<%= javascript_tag "$('item_title').focus()" %>

I have tried with Javascript

<script type="text/javascript">
  document.getElementById("item_title").focus();
</script>

Nothing works. I am testing with a Firefox 28 browser. I have seen many examples that suggest those ways should work. There is nothing else in play here - this is a basic form rendered by a controller action. It isn't using Bootstrap modals.

I have checked that input_title is the field's id by using Javascript to set its value - that works.

Any suggestions much appreciated.

尝试这个

<%= f.input :title, label: t('.title'), input_html: {:autofocus => true} %>

只需在您的div中添加类

<%= f.input :title, label: t('.title'), class: "form-control"  %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM