Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

How do you get the Ruby on Rails generated id of a form element for reference in JavaScript?

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 %>
question from:https://stackoverflow.com/questions/4819696/how-do-you-get-the-ruby-on-rails-generated-id-of-a-form-element-for-reference-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...