Setting the focus in a form
Posted by Jim Morris on Sun Oct 29 15:40:38 -0800 2006
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
:
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.
You can also use prototype/scriptaculous and type:
Element.focus('domid');
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.
You can simplify your helper to three lines, thanks to prototype:
def set_focus_to_id(id)
javascript_tag("$('#{id}').focus()");
end
Thanks for sharing this useful little snippet, it slotted into what I'm doing and worked first time!
This worked great until I pointed IE6 at it and the page appeared blank even though the source could be seen and was valid. Finally figured out that resizing the window manually made it visible and so I added:
if (navigator.appVersion < "7"
&& navigator.appName == "Microsoft Internet Explorer")
{
function winalign()
{
window.resizeBy(-10,-10);
setTimeout("window.resizeBy(10,10);",200);
}
window.onload=function(){winalign();};
}
If there is a less ugly way to make this work, I'd love to know.
I suspect this has something to do with the timing of when the script is executed, and whether the page has fully loaded. JQuery has a solution to this with the $(document).ready(function() {
// do stuff when DOM is ready
});
So if you were to put the javascript in that function I suspect it will work even on a broken IE6
After much googling....your's was the most elegant and simple!
Thanks!
To resolve IE6 issues. Works in other browsers as well.
document.observe("dom:loaded", function() {
$('my_control_id').focus()
});