NeoArch

February 29, 2008

Setting Focus in Rails with Prototype

Filed under: Javascript, Rails — Jason @ 11:28 am
Tags: , , , , ,

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

1 Comment »

  1. Hi
    I have a div “reason_for_transfer_search_sd” like

    “service_desk_part/on_action_transfer_reason_sd_search”, :locals => {:sd_ticket=>sd_ticket } %>

    And in on_action_transfer_reason_sd_search
    “50×1″ %>
    “‘transfer_reason=’ + $(’transfer_reason’).value”,
    :url => { :controller => :service_desk,:action =>
    :edit_service_desk_status_after_transfer_from_search_sd,
    :sd_id => sd_ticket.id,
    } },
    %>

    So to focus cursor to this textarea I used
    just below that and it is
    working properly. And in appliation helper
    def set_focus_to_id(id)
    javascript_tag(”$(’#{id}’).focus()”);
    end
    But my problem is i am replacing the same div from the controller after processing using rjs..But this time cursor focus does not goes to text area.What might be the reason?

    Thanks in advance
    Sijo

    Comment by sijo — May 26, 2008 @ 4:36 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.