Focus On Form Element
Ruby on Rails supports forms very comfortably: generating a form from a model, updating data of a model or validating input values. But I always missed one functionality: to set a focus on an element.
It is quite frustrating: a form shows in your browser, you start typing and you are overwriting the actual URL or you are typing to a quick find box. Well, it is my fault, because I did not check if the text cursor | is blinking in one of the form input boxes, so then I click to a wanted input box and, finally, I am typing to the right box :)
But there is a way how to save a movement with a mouse and one mouse click: to set the focus on one of the form elements. (Btw. you can also use the Tab
key, but I need to press it 4-times to get to the first input box on a form in my Firefox. Surprisingly, I do not use this way so often. :)
I. Without Focus
Let’s take a form generated by the scaffold generator (for a model called user
that contains items first_name
and last_name
).
-
<p><label for="user_first_name">First name</label><br/>
-
<%= text_field ‘user’, ‘first_name’ %></p>
-
<p><label for="user_login_name">Last name</label><br/>
-
<%= text_field ‘user’, ‘login_name’ %></p>
The code is displayed in a browser without a text cursor, i.e. none of the input text boxes is focused. For example see the following screenshot:
II. Helper Template Method
The focus can be set with a JavaScript code element.focus()
, but we will do it in more RoR way :)
Open the ApplicationHelper
module, located in the app/helpers/application_helper.rb
file, and add there a method set_focus
:
-
span style=”color:#996600;”>"$(‘#{id}’).focus()"
The set_focus
method takes an element (specified by its id) and generates a JavaScript code to set the focus. (Tested and it works OK on Firefox and Konqueror; IE sets the focus during loading the page, but when the page is fully loaded, the focus disappears.)
III. With Focus
The focus will be set with the above mentioned method set_focus
:
-
<%= set_focus ‘first_name’ %>
The method should be called after the specified element, e.g. a good place is after the whole form definition.
The form is displayed in a browser with a text cursor, i.e. the First name input text box is focused. For example see the following screenshot:
Enjoy :)