How do you get the Ruby on Rails generated id of a form element for reference in JavaScript?
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
Look at the form builder options:
<%= form_for @user do |f| %>
<% form_css_id = "#" + f.options[:html][:id] %>
<% end %>
Options should at least include the following data: css class, id, http method and authenticity token.
In case someone has a FormBuilder object from a fields_for
block, it is possible to get its id
using this snippet:
<%= form.fields_for :something do |fields_form| %>
<%= fields_form.object_name.gsub(/[\[\]]+/, '_').chop %>id
<% end %>
FieldsForm#object_name
returns the field's ID as something like this: user[address][0]
. Next, the regex substitution changes groups of one or more brackets to underscores. This substitution leaves a trailing underscore, to which it appends the letters id
. For the example provided before, this results in user_address_0_id
.