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

前端 未结 8 883
無奈伤痛
無奈伤痛 2021-02-05 01:01

When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the element that it outp

8条回答
  •  有刺的猬
    2021-02-05 01:48

    You'll want to specify the id yourself. Here generating the id from the object_id of the form guarantees that it won't conflict with another text_field for username in the case of nested forms.

    <%= form_for @user do |f| %>
      <%- id = "username_#{f.object_id}" %>
      <%= f.text_field :username, :id=>id %>
    <% end %>
    
    <%= javascript_tag do %>
      $("##{id}").doSomethingReallyCool();
    <% end %>
    

提交回复
热议问题