Setting the focus in a form
Posted by Jim Morris Sun, 29 Oct 2006 23:40:38 GMT
This is a simple one, how do I set the focus in the first item in my form?
Put this in your app/helpers/application_helper.rb:
# put this in the body after a form to set the input focus to a specific control id
def set_focus_to_id(id)
<<-END
<script language="javascript">
<!--
document.getElementById("#{id}").focus()
//-->
</script>
END
endThen in your .rhtml file somewhere after the form is defined add this
<%= set_focus_to_id 'user_login' %>
where user_login will be the id of the field you want to get the focus.
An example of a login form...
<p>
Please Login
</p>
<% form_for :user do |f| %>
<label for="user_login">Login</label>
<%= f.text_field :login, :tabindex => "1" %>
<br />
<label for="user_password">Password</label>
<%= f.password_field :password, :tabindex => "2" %>
<br />
<label for="user_remember_me">Remember me:</label>
<%= f.check_box :remember_me, :tabindex => "0" %>
<br />
<%= submit_tag 'Log in', :tabindex => "3" %>
<br />
<% end %>
<%= set_focus_to_id 'user_login' %>
When the login form is shown the focus will be set to the login text field. Of course java script needs to be enambled otherwise they will have to do it manually.