Wolfmans Howlings

A programmers Blog about Ruby, Rails and a few other issues

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
  end

Then 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.

Posted in  | Tags , ,  | 3 comments | no trackbacks

Comments

  1. Chad H said about 1 hour later:

    You can also use prototype/scriptaculous and type:

    Element.focus('domid');

  2. wolfman said about 4 hours later:

    Thats cool thanks, the reason I posted this is because 10 minutes of Googling didn't bring up too many Rails specific methods to do it.

  3. eric said about 1 month later:

    You can simplify your helper to three lines, thanks to prototype:

    def set_focus_to_id(id)
      javascript_tag("$('#{id}').focus()");
    end
    

Trackbacks

Use the following link to trackback from your own site:
http://blog.wolfman.com/articles/trackback/67

(leave url/email »)

   Comment Markup Help Preview comment