Archive for February 2008
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
cap -A seems to be deprecated
This is just a FWIW in regards to Capistrano. Capistrano is a piece of software (a Ruby Gem, to be more specific) that I use to automatically deploy applications to web servers. I recently upgraded to version 2.1.0.
Previously, to set up an application under Capistrano, I would run the command cap -A .
That period at the end is part of the code.
In the new version of Capistrano, that seems to be deprecated. You now have to run capify .
So, now you know, and now I have a way to remember it.