starfry
starfry

Reputation: 9943

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.

Upvotes: 3

Views: 1156

Answers (2)

rsilvino
rsilvino

Reputation: 21

Try this

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

Upvotes: 2

santosh
santosh

Reputation: 1611

Just add class to your div

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

Upvotes: 0

Related Questions