Sunday, May 19, 2024
85
rated 0 times [  92] [ 7]  / answers: 1 / hits: 16460  / 14 Years ago, thu, january 27, 2011, 12:00:00

When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the <input /> element that it outputs. How can I generate the same id for later inclusion into JavaScript generated later?



<%= form_for @user do |f| %>
<%= f.text_field :username %>
<% end %>


Then later in the page:



<%= javascript_tag do %>
$('<%= id of the :username field %>').doSomethingReallyCool();
<% end %>

More From » ruby-on-rails

 Answers
61

I ended up creating a custom form builder to expose the property directly



class FormBuilder < ActionView::Helpers::FormBuilder
def id_for(method, options={})
InstanceTag.new( object_name, method, self, object )
.id_for( options )
end
end

class InstanceTag < ActionView::Helpers::InstanceTag
def id_for( options )
add_default_name_and_id(options)
options['id']
end
end


Then set the default form builder



ActionView::Base.default_form_builder = FormBuilder 

[#94020] Wednesday, January 26, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;