Posts Tagged ‘fields’
Setting Focus in Rails with Prototype
Recently, I tried for a day to set focus on a field within a form that I had created for a Rails application. It was more difficult than you might think. So, here are my instructions for anyone else who may be trying to do this.
Rails usually comes packaged with several Javascript frameworks that can make life much easier. One of these, prototype, allows us to set focus on a field.
Here’s how you do it. In your application_helper.rb file, include the following lines:
def set_focus_to_id(id)
javascript_tag("$('#{id}').focus()");
end
In your layout either for the application or the controller, include this line in the meta section:
<%= javacript_include_tag "prototype" %>
If you wanted to include all the javascript libraries, you could include this line, but it hogs bandwidth:
<%= javacript_include_tag :defaults %>
In your rhtml file that contains the field you want to set focus on, include this line:
<%= set_focus_to_id 'password' %>
Note that your id is to be the id of the field you want to set focus on. If you are using this with a form, a fine place to insert the line is right after the end tag for the form.
That’s it. If you’ve done all that, you should have focus on the field.
HT: Wolfman