port5432
port5432

Reputation: 6403

Autofocus not working in rails

I've got a button in my Rails app, and would like to have it set to autofocus, so the user can just hit enter to move on when the page is loaded.

The code below is not working: the button is working but it is not set to autofocus.

<%= link_to new_flashcard_flashcard_test_path(@flashcard_deck.next_flashcard), :class => 'btn btn-primary', :autofocus => true do %>
      <span class="glyphicon glyphicon-link"></span>
      Next card
<% end %>

Generated HTML

<a autofocus="autofocus" class="btn btn-primary" href="/flashcards/1188/flashcard_tests/new">
  <span class="glyphicon glyphicon-link"></span>
  Next card
</a>

Upvotes: 2

Views: 1776

Answers (2)

goodbedford
goodbedford

Reputation: 95

I had this same problem.

I would suggest putting the autofocus into your form with rails by using autofocus: true instead of using Jquery, thats over kill. I hope this helps someone.

<%= form_for @user do |f| %>
    <%= f.label :username %>:
     <%= f.text_field :username,autofocus: true, class:"form-control" %><br />
     <%= f.label :email %>:
     <%= f.email_field :email, class:"form-control" %><br />
     <%= f.label :password %>:
     <%= f.password_field :password, class:"form-control" %><br />
     <%= f.submit "Sign Up", class:"btn btn-primary" %>
  <% end %>

Upvotes: 6

Christian Rolle
Christian Rolle

Reputation: 1694

HTML5 attribute autofocus is just for input fields, like

<input autofocus/>

Please read about it at w3schools You can achieve the same with some Javascript (used jQuery for the example):

jQuery(document).ready(function(){
  $('*[autofocus]').focus()
})

Upvotes: 2

Related Questions